I am trying to check wether mylist
contains a given object or not, where mylist
is an 开发者_Python百科ArrayList
of type myCustomClass
.
If you add an instance of MyCustomClass
to the list, and then check if it contains another instance of MyCustomClass
, it will always return false, unless you override the equals
method in your custom class. The equals method checks if another object is functionally equal to this object.
Make sure to override the hashCode
method each time you override the equals method. hashCode
should return the same value for two equal objects. Also, equals should be written so that it's symmetric: a.equals(b)
if and only if b.equals(a)
.
Check equals and hashCode in the javadoc of java.lang.Object
.
You most likely haven't implemented equals()
and hashcode()
on myCustomClass
. You need to implement them properly and according to contract, see here for details of how.
精彩评论