0

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?

4
  • Your code is too partial, at least include the methods you've implemented and are using inside this method Commented Dec 19, 2018 at 20:11
  • what does your contains function look like. That looks like the problem Commented Dec 19, 2018 at 20:16
  • How do I successfully merge array objects in a super class And where is that merging? Commented Dec 19, 2018 at 20:24
  • So BetterBasket extends Basket which extends ArrayList? Have you overridden contains() or is the contains method only defined in ArrayList? If you haven't overridden it does your Product class have adequate equals() and hashcode() methods to make ArrayList.contains(Object obj) work they way you expect it to? Commented Dec 19, 2018 at 21:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.