I have a question. I cant solve it and I need some help please. I have an Arraylist of objects then I have a method where objects are created and added to the Arraylist but I want another method where I can print the Arraylist but everytime I try the Arraylist is empty so this is my code:
public class Packages{
ArrayList<Pack> myList = new ArrayList<Pack>();
Pack obj;
public double addPackage(int type, double num){
if(type==1)
{
obj = new Pack(type, num);
total = obj.calculateTotal;
}
else
{
obj = new Pack(type, num);
total = obj.calculateTotal;
}
myList.add(obj);
return total;
}
public int listSize(){
return myList.size();
}
}
Everytime I call the listSize() method it returns 0, looks like when the addPackage method finishes it deletes the objects I added to my Arraylist.
Note: my addPackage method is going to return a double total but at the same time add the objects I create to the arraylist. I need some help please.
I tried your code and it is almost right. I am posting the classes again which I used and which work:
public class Package {
List<Pack> myList = new ArrayList<Pack>();
Pack obj;
double total = 0;
public double addPackage(int type, double num) {
if (type == 1) {
obj = new Pack(type, num);
total = obj.calculateTotal();
} else {
obj = new Pack(type, num);
total = obj.calculateTotal();
}
myList.add(obj);
return total;
}
public int listSize() {
return myList.size();
}
}
Now class Pack is:
public class Pack {
int type;
double value;
public Pack(int type, double value) {
this.type = type;
this.value = value;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public double calculateTotal() {
return type*value;
}
}
And I verified in this code:
public static void main(String[] args) {
Package pkg = new Package();
pkg.addPackage(10,10);
pkg.addPackage(10,20);
System.out.println(pkg.listSize());
}
And as expected it returns 2. All these classes may not exactly be same as what you have but it will give you the idea about what are you missing.
Related
As I'm going though the debugger it looks like it is working at first, however when I try calling getCoordinates() in my shipSunk() method, it returns a null value almost every time. What is wrong here?
public boolean shipSunk(ShipDerived[] s){
ArrayListMultimap<Integer, Integer> temp;
ArrayList<Integer> temp2 = new ArrayList<>();
boolean sunk = false;
for(int i=s.length-1; i>=0;i--){
Ship st = s[i];
temp = s[i].getCoordinates(); //returns null almost every time???
temp2 = s[i].getCoordinatesList();
for (Map.Entry<Integer, Integer> entry : temp.entries()){
//System.out.println(entry.getKey() + ", " + entry.getValue());
if(grid[entry.getKey()][entry.getValue()]=='x'){
sunk = true;
}
else{
sunk = false;
}
}
if(sunk==true){
System.out.println("Ship has been sunk!");
}
temp.clear();
}
return sunk;
}
And here is my Ship class (extended from abstract class) methods:
import java.util.ArrayList;
public class ShipDerived extends Ship{
private String type;
private int length;
private ArrayListMultimap<Integer, Integer> coordinates = ArrayListMultimap.create();
private ArrayList<Integer> c2 = new ArrayList<>();
public ShipDerived(){
this.type = type;
this.length = length;
this.coordinates = getCoordinates();
this.c2 = getCoordinatesList();
}
public ShipDerived(String t, int l){
this.type = t;
this.length = l;
this.coordinates = getCoordinates();
this.c2 = getCoordinatesList();
}
#Override
void setType(String t) {
type = t;
}
#Override
void setLength(int l) {
length = l;
}
#Override
String getType() {
return type;
}
#Override
int getLength() {
return length;
}
#Override
ArrayListMultimap<Integer, Integer> getCoordinates() {
return this.coordinates;
}
ArrayList<Integer> getCoordinatesList() {
return this.c2;
}
#Override
void setCoordinates(int i, int j) {
//coordinates.putAll(i, Collections.singleton(j));
this.coordinates.put(i,j);
this.c2.add(i);
this.c2.add(j);
}
}
Here is my Ship (abstract) class:
public abstract class Ship {
private int length;
private String type;
private ArrayListMultimap<Integer, Integer> coordinates;
Ship(){
this.length = length;
this.type = type;
}
abstract void setType(String t);
abstract void setLength(int l);
abstract String getType();
abstract int getLength();
abstract ArrayListMultimap<Integer, Integer> getCoordinates();
abstract void setCoordinates(int i, int j);
}
And this is what I am passing into my shipSunk() method. I an using getters/setters to create my ships:
p1board.shipSunk(p1.getShips()); //player 1
p2board.shipSunk(p2.getShips()); //player 2
These seem to work but here's some code into these as well:
public class Player {
private String name;
private ShipDerived[] ships = new ShipDerived[5];
public Player(){
this.name = name;
this.ships = ships;
}
public String getName(){
return name;
}
public void setName(String x){
name = x;
}
public void setShips(){
int a = 0;
for(int i=5; i>=1;i--){
ShipDerived s = new ShipDerived("null", 0);
Array.set(ships, a, s);
a++;
}
ships[0].setType("carrier");
ships[0].setLength(5);
ships[1].setType("battleship");
ships[1].setLength(4);
ships[2].setType("destroyer");
ships[2].setLength(3);
ships[3].setType("submarine");
ships[3].setLength(3);
ships[4].setType("patrol boat");
ships[4].setLength(2);
}
public ShipDerived[] getShips(){
return ships;
}
You initialize this.coordinates twice. First as an inline field initializer and second in the constructor. The statement this.coordinates = getCoordinates(); does not make sense because the getter returns this.coordinates, so you effectively get this.coordinates = this.coordinates;
This shouldn't effect your issue, but my recommendation for easier debugging is to just set all fields that you can to final to avoid issues such as this and remove the superfluous call from the constructor.
Then I would investigate the ArrayListMultimap.create(); method, if there is any way that one returns null.
You have #Override annotation on getCoordinates() so I'm guessing your Ship class also have coordinates field. In shipSunk method you cast your object to Ship class so most likely it operate on field Ship.coordintes whis is null because you are initializing only DerivedShip.coordinates.
Check this for simple example of hiding fields: If you overwrite a field in a subclass of a class, the subclass has two fields with the same name(and different type)?
There are so many strange things in your code:
Why has the Ship class private fields if you don't provide access methods for those fields? Without accessor methods nobody can use those fields, so just delete them!
Why do the ShipDerived constructors initialize the coordinates and c2 fields if you already initialize them at the declaration?
Why does Player.setShips() use some obscure Array.set(ships, a, s); when ships[a] = s; would be sufficient?
Why do your constructors (for Ship, ShipDerived and Player) contain nonsense-code like this.type = type; (in ShipDeriveds default constructor) that seems important but does nothing?
Why does the Player.setShips() method create empty ShipDerived instances and only afterwards sets their values?
After some cleanup your classes could look like:
Ship.java:
import com.google.common.collect.ArrayListMultimap;
public abstract class Ship {
Ship(){
}
abstract void setType(String t);
abstract void setLength(int l);
abstract String getType();
abstract int getLength();
abstract ArrayListMultimap<Integer, Integer> getCoordinates();
abstract void setCoordinates(int i, int j);
}
ShipDerived.java:
import java.util.ArrayList;
import com.google.common.collect.ArrayListMultimap;
public class ShipDerived extends Ship{
private String type;
private int length;
private ArrayListMultimap<Integer, Integer> coordinates = ArrayListMultimap.create();
private ArrayList<Integer> c2 = new ArrayList<>();
public ShipDerived(){
}
public ShipDerived(String t, int l){
this.type = t;
this.length = l;
}
#Override
void setType(String t) {
type = t;
}
#Override
void setLength(int l) {
length = l;
}
#Override
String getType() {
return type;
}
#Override
int getLength() {
return length;
}
#Override
ArrayListMultimap<Integer, Integer> getCoordinates() {
return this.coordinates;
}
ArrayList<Integer> getCoordinatesList() {
return this.c2;
}
#Override
void setCoordinates(int i, int j) {
this.coordinates.put(i, j);
this.c2.add(i);
this.c2.add(j);
}
}
Player.java:
public class Player {
private String name;
private ShipDerived[] ships = new ShipDerived[5];
public Player(){
}
public String getName(){
return name;
}
public void setName(String x){
name = x;
}
public void setShips(){
ships[0] = new ShipDerived("carrier", 5);
ships[1] = new ShipDerived("battleship", 4);
ships[2] = new ShipDerived("destroyer", 3);
ships[3] = new ShipDerived("submarine", 3);
ships[4] = new ShipDerived("patrol boat", 2);
}
public ShipDerived[] getShips(){
return ships;
}
}
These changes might not yet solve your issue, but at least make your code easier to read and understand.
Actually, since the Ship class no longer contains any fields and has only abstract methods you could even turn it into an interface (but that would mean that your methods are now public instead of package private, which would mean that you would also need to declare them as public in ShipDerived).
Ship.java, interface version:
import com.google.common.collect.ArrayListMultimap;
public interface Ship {
void setType(String t);
void setLength(int l);
String getType();
int getLength();
ArrayListMultimap<Integer, Integer> getCoordinates();
void setCoordinates(int i, int j);
}
I am trying to build an ArrayList that will contain objects. when i add an object to the list i want it to first check the array list for that object. and if it finds it i want it to increase a quantity variable in that object and not create a new object in the list. and then vice versa when removing objects. I have accomplished a way that works when removing an object. But i dont think i fully understand the methods in the arraylist or the logic when creating and arraylist of objects. as when i use .contains or .equals im not getting the desired effect.
public class ItemBag {
private ArrayList<Item> inventory = new ArrayList<Item>();
public ItemBag() {
}
public void addItem(Item objName, int quantity) {
if (inventory.contains(objName)) {
System.out.println("if statement is true!");
int i = inventory.indexOf(objName);
inventory.get(i).setQuantity(inventory.get(i).getQuantity() + quantity);
} else {
inventory.add(objName);
objName.setQuantity(quantity);
}
}
public void removeItems(String itemName, int quantiy) {
for (int i = 0; i < inventory.size(); i++) {
if (inventory.get(i).name() == itemName) {
inventory.get(i).setQuantity(inventory.get(i).getQuantity() - quantiy);
if (inventory.get(i).getQuantity() <= 0) {
inventory.remove(inventory.get(i));
}
}
}
}
public void showInventory() {
for (int i = 0; i < inventory.size(); i++) {
System.out.println(inventory.get(i).name() + " : " + inventory.get(i).getQuantity());
}
}
then when creating the itemBag in another object i am writing
ItemBag merchantItems = new ItemBag();
public void merchantBob() {
merchantItems.addItem(new HealthPotion() ,3);
merchantItems.showInventory();
System.out.println("add 1");
merchantItems.addItem(new HealthPotion(),1);
merchantItems.showInventory();
Items class
package Items;
public abstract class Item {
private int quantity = 0;
public Item() {
}
public abstract String name();
public abstract int cost();
public abstract String type();
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
HealthPotion Class
public class HealthPotion extends Potions {
protected int addHealth = 10;
#Override
public int drinkPotion() {
return addHealth;
}
#Override
public String name() {
return "Health Potion";
}
#Override
public int cost() {
return 5;
}
#Override
public String type() {
return "Potion";
}
}
The .contains() method would iterate through the list and use .equals() method to compare each element and check if the provided object exists in the list.
.equals() method would compare the object reference (unless .equals() is overridden) to check if the objects are same.
For reference: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#contains-java.lang.Object-
You can override the .equals() method to compare the values of the provided object in the following way:
public abstract class Item {
private int quantity = 0;
public Item() {
}
public abstract String name();
public abstract int cost();
public abstract String type();
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
#Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Item providedItem = (Item) object;
return name == providedItem.name
&& cost == providedItem.cost
&& type == providedItem.type;
}
}
This should work
I need to sort a java list containing objects of type Hotel
List<Hotel> hotelList = new ArrayList<>();
Inside the class I do have the method
#Override
public List<Room> getAvailableRooms() {
return this.rooms;
}
I need to sort my hotelList by the price attribute found in Room class.
Any suggestions?
You should either use a Comparator or implement the Comparable interface
public class Foo implements Comparable<ToSort> {
private int val;
public Foo(int val){
this.val = val;
}
#Override
public int compareTo(ToSort f) {
if (val > f.val) {
return 1;
}
else if (val < f.val) {
return -1;
}
else {
return 0;
}
}
Read more here
https://dzone.com/articles/sorting-java-arraylist
I am trying to write a method in which I need to create a temp variable, sum, of generic type T. However, I'm getting the error "The local variable sum may not have been initialized". How can I initialize a generic variable? I can't set it to 0 or 0.0, and I can't find information anywhere on how to deal with this. Here is the portion of code that I'm working with:
public Matrix<T,A> multiply(Matrix<T,A> right) throws MatrixException
{
Matrix<T,A> temp = new Matrix<T,A>(arithmetics, rowSize, columnSize);
T sum, product;
if (rowSize != right.columnSize)
throw new MatrixException("Row size of first matrix must match column size "
+ "of second matrix to multiply");
setup(temp,rowSize,columnSize);
for (int i = 0; i < rowSize; i++){
for (int j = 0; j < right.columnSize; j++) {
product = (arithmetics.multiply(matrix[i][j] , right.matrix[j][i]));
sum = arithmetics.add(product, sum);
temp.matrix[i][j] = sum;
}
}
return temp;
}
I'm not sure if this will help clarify, but here is my interface Arithmetics:
public interface Arithmetics<T> {
public T zero();
public T add( T a, T b );
public T subtract( T a, T b);
public T multiply (T a, T b);
public T parseString( String str );
public String toString( T a );
}
And here is one of my classes, DoubleArithmetics, just to show how I'm implementing the interface:
public class DoubleArithmetics implements Arithmetics<Double> {
protected Double value;
public Double zero()
{
return new Double(0);
}
public Double add( Double a, Double b )
{
return new Double(a.doubleValue()+b.doubleValue());
}
public Double subtract (Double a, Double b)
{
return new Double(a.doubleValue()-b.doubleValue());
}
public Double multiply (Double a, Double b)
{
return new Double(a.doubleValue()*b.doubleValue());
}
public Double parseString( String str )
{
return Double.parseDouble(str);
}
public String toString( Double a )
{
return a.toString();
}
}
Just use the zero method that you already have on your interface to initialize sum:
T sum = arithmetics.zero();
For the non-zero initialization, you could also add methods that take long and double values and return the T for them:
public interface Arithmetics<T> {
public T zero();
public T create(long l);
public T create(double d);
public T add( T a, T b );
public T subtract( T a, T b);
public T multiply (T a, T b);
public T parseString( String str );
public String toString( T a );
}
And then implement them:
public Double create(long l) {
return new Double(l);
}
public Double create(double d) {
return new Double(d);
}
And finally, to use them:
T one = arithmetics.create(1);
Instantiating generics in Java is a bit tricky due to type erasure.
My approach is to pass into your generic class' constructor two items: (1) a java.lang.reflect.Constructor specific to type T; and (2) an Object[] array holding a default value specific to type T.
When you later want to instantiate and initialize a type T, you need to call Constructor.newInstance(Object[]). In the code below, the MyGenericClass class stands in for your generic class (looks like it's called Matrix from your original post).
I got the solution from InstantiationException for newInstance() and Create instance of generic type in Java?
public class MyGenericClass<T>
{
Constructor _constructorForT;
Object[] _initialValueForT;
public MyGenericClass(Constructor constructorForT,
Object[] initialValueForT)
{
_constructorForT = constructorForT;
_initialValueForT = initialValueForT;
}
public void doSomething()
{
T sum = initializeT(_constructorForT, _initialValueForT);
System.out.printf("d = %f\n", sum);
}
#SuppressWarnings("unchecked")
private T initializeT(Constructor constructor, Object[] args)
{
T result = null;
try
{
result = (T) constructor.newInstance(args);
}
catch (java.lang.InstantiationException ex)
{
}
catch (java.lang.IllegalAccessException ex)
{
}
catch (java.lang.reflect.InvocationTargetException ex)
{
}
return result;
}
public static void main(String argv[]) throws Exception
{
Constructor constructor =
Double.class.getConstructor(new Class[]{double.class});
Object[] initialValue = new Object[] { new Double(42.0) };
MyGenericClass<Double> myGenericClass =
new MyGenericClass<Double>(constructor, initialValue);
myGenericClass.doSomething();
}
}
I have a class called x which is a array list and needs to be sorted in Decreasing order by Value.
My Class-
public static class x
{
public int id;
public double value;
public x(int _id, double _value)
{
id = _id;
value = _value;
//System.out.println(Integer.toString(id));
}
public Integer getID(){
return id;
}
public double getValue(){
return value;
}
//Sorting
public static Comparator<x> getComparator(SortParameter... sortParameters) {
return new xComparator(sortParameters);
}
public enum SortParameter {
VAL_DESCENDING
}
private static class xComparator implements Comparator<x> {
private SortParameter[] parameters;
private xComparator(SortParameter[] parameters) {
this.parameters = parameters;
}
public int compare(x o1, x o2) {
int comparison;
for (SortParameter parameter : parameters) {
switch (parameter) {
case VAL_DESCENDING:
comparison = o2.id - o1.id;
if (comparison != 0) return comparison;
break;
}
}
return 0;
}
}
}
I Call it like:
cp = x.getComparator(x.SortParameter.VAL_DESCENDING);
Collections.sort(attr1, cp);
attr1 is my array list
Just for Reference I am following this
I am getting error:
cannot find symbol : variable cp
I am a newbie to java :(
try using Comparator<x> cp = x.getComparator(x.SortParameter.VAL_DESCENDING); to declare it. you can not use a variable until it is declared