Reputation: 16385
I have many classes that implement a common interface. I use a definition like Array List mytypes, and add objects of that type to the ArrayList. Now i want to use contains method of the ArrayList class to see if this List contains a class i am adding.
If I implement hashcode
and equals
on the classes will the contains method know if a certain object already is in the ArrayList or not?
Upvotes: 0
Views: 743
Reputation: 178421
from List.contains()
:
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
So basically hashCode()
is not relevant here, only equals()
EDIT: [better explicit then implicit], as mentioned in comments by @aiobee, equals()
still needs to be overriden - according to the contract - but it will not have effect on the value returned by contains()
Upvotes: 2
Reputation: 1500065
ArrayList.contains
won't use hashCode
, but it will use equals
, as documented:
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
(This won't check whether "this class" is already in the list - it will check whether an equal object is in the list.)
Upvotes: 1
Reputation: 47608
Implementing hashCode is not useful for that purpose but it is a goog practice to override both equals and hashCode simultaneously.
Yes, it will work, that is the purpose of the contains method.
Upvotes: 1