Reputation:
HashMap<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("id", maxRowId);
hashMap.put("item", item_name);
hashMap.put("price", price);
hashMap.put("quantity", quantity);
hashMap.put("total", total);
//customItemArrayList.add(hashMap);
// int id = Integer.parseInt(customItemArrayList.get(position).get("id").toString());
for(int i = 0; i < customItemArrayList.size(); i++)
{
//System.out.println(namesList.get(i));
String name = customItemArrayList.get(i).get("item").toString();
if (name.equals(item_name)){
Toast.makeText(getContext(), "It exists",Toast.LENGTH_LONG).show();
i = customItemArrayList.size();
} else {
customItemArrayList.add(hashMap);
//i = customItemArrayList.size();
}
}
maxRowId++;
I have an object ArrayList with a hashmap. Before adding an item, I check if an item already exists with a similar name. if it exists, it should not be added again. The above code does show that the item exists, however, it goes ahead to add the item. What could be wrong with it?
Upvotes: 0
Views: 40
Reputation: 111269
You are adding the new item when you find an item that has a different name. Let's say you're adding an item with name "bernard" and your list has items with names "alice" and "bernard": The new item gets added because "alice" is not "bernard".
To fix, add a boolean variable that tells you if a match has been found. Initially it's set to false. If you find a match, you change it to true. Afterwards, you check if a match was found, and if not, only then add the new item.
boolean exists = false;
for (int i = 0; i < customItemArrayList.size(); i++) {
//System.out.println(namesList.get(i));
String name = customItemArrayList.get(i).get("item").toString();
if (name.equals(item_name)) {
exists = true;
break;
}
}
if (!exists) {
customItemArrayList.add(hashMap);
//i = customItemArrayList.size();
}
Upvotes: 2
Reputation: 5246
The issue is that you're looping through the entire collection and checking if an entry exists. On each equality check, its possible that the entry you're comparing against isn't the equal entry so it passes the check. You need to check all entries first and then if nothing is found, add.
Upvotes: 1