I have a subclass BetterBasket
that inherits from a superclass Basket
, which itself inherits from ArrayList<Product>
. My method add
in BetterBasket
adds an item searched through the ArrayList
and if there is an object of the same type then the values must be added to the already existing object (merge the quantity
and price
), and if not the object must be added into the ArrayList
. This is my code but it won't work properly, as it will add the products as needed but will not merge the same products. So it doesn't use the else part of the code.
@Override
public boolean add(Product pr)
{
if (!this.contains(pr)){ //if array doesn't contain the item
super.add(pr); //adds item
} else { //add item quantity and price to existing item.
double x = pr.getPrice();
int q = pr.getQuantity();
for (int i=0; i < super.size(); i++) //loop through array
{
if (super.get(i).equals(pr)){ //if item is same as item within
//the array
int w = super.get(i).getQuantity();
double y = super.get(i).getPrice();
super.get(i).setQuantity(q + w);
super.get(i).setPrice(y + x);
}
}
}
return true;
}
Should I use this
or super
for the first if
statement? Why is the else
branch not being used?