I’m a little befuddled by some code:
for (AbstractItem item : mSetOfItems) {
if (item.equals(pPrimaryItem))
{
System.out.println("Contains? " + mSetOfItems.contains(pPrimaryItem));
}
}
How could it be possible that item.equals(pPrimaryItem) resolves as true, and mSetOfItems.contains(pPrimaryItem) resolves as false? Because that’s what I’m seeing in my code.
In other words, if I iterate through my set, I can find an element equal to my test element. But if I use contains, my test elements is not reported being in the set. I’m baffled because I thought contains used equals. What could I be overlooking?
You didn’t give the type of
mSetOfItems, but I’m guessing thatAbstractItemoverrides.equals()but not.hashcode(). This is bad.If
mSetOfItemsuses hashcode for lookup, which it could based on its type, you’ll get the behavior you described.Your assumption is that
.contains()is implemented with iteration and.equals(). There’s no list interface which guarantees that.