2

I have a list of a custom class object I created.


private List<Grocery> groceryList;

where Grocery class has name, price , quantity variables and getters... And I want to check if a grocery product already exist in my list or not,if doesn't exist I want to add it to my list, here is my code:

CheckOut hisCheckOut = new CheckOut(itemName ,String.valueOf(price), String.valueOf(orderQuantity), String.valueOf(itemTotalPrice));


    if(!(GroceryActivity.list.contains(itemName))){
        GroceryActivity.list.add(hisCheckOut);
        GroceryActivity.totalItemsPrice += itemTotalPrice;
    }

itemName is a variable with a normal string name .This is not working.

Cleo
  • 136
  • 1
  • 10
warCommander
  • 392
  • 4
  • 19

2 Answers2

1

Your code is not working because you are checking itemName and the item itself.

Do it as follows:

boolean found=false;
for(Grocery g: GroceryActivity.list){
    if(g.getItemName().equals(itemName)){
        found=true;
        break;
    }
}
if(!found){
    //...do whatever you want to do
}

Where itemName is the name of the item you want to checkout and getItemName is the getter of itemName in class Grocery.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

The Grocery and the CheckOut are entirely different objects and you cannot actually compare two different types of objects using equals or contains. If you CheckOut class holds more items than the Grocery object, then I would recommend adding the Grocery object itself as an attribute to the CheckOut object so that you can use the comparison methods.

Hence the CheckOut class may look like as follows.

public class CheckOut {
    public long checkOutTime; 
    // ... other extra attributes can go here

    // Add the Grocery object as an attribute
    public Grocery groceryItem; 
}

Now when creating the CheckOut object, you are basically creating a grocery item in it, and now you can compare with the list of items that you have in your GroceryActivity.

boolean itemAdded = false;
for (CheckOut checkout : GroceryActivity.list) {
    if (checkout.groceryItem.getName().equals(itemName) {
        // Already added to the checkout
        itemAdded = true;
        break;
    }
}

if (!itemAdded) {
    GroceryActivity.list.add(hisCheckOut);
    GroceryActivity.totalItemsPrice += itemTotalPrice;
}

I hope that helps!

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98