-1

I am trying to check wether mylist contains a given object or not, where mylist is an ArrayList of type myCustomClass.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Krishna Shrestha
  • 1,662
  • 14
  • 38
  • check this question http://stackoverflow.com/questions/2642589/how-does-a-java-arraylist-contains-method-evaluate-objects – Rangi Lin Aug 28 '11 at 09:41

2 Answers2

3

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

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.

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
  • should i overide the equal() method in mycustom class ?? istnt it property of list interface??? confused?? anyways thanks for qick reponse – Krishna Shrestha Aug 28 '11 at 09:53
  • @chrish Yes you should and no it is not a "property of the list interface". – Jesper Aug 28 '11 at 10:04
  • @chrish yes, override equals on the mycustom class - and it's good practice to annotate it with the "Override" annotation (it's ATSIGNoverride, can't use the at sign there for some reason) so it's definitely overriden (the compiler will complain if you use the annotation and it's not.) There's no such things as "properties" in Java (not like in C# anyway.) – Michael Berry Aug 28 '11 at 10:16
  • thanks @berry120 ,@Jesper i override equals (obj) method and it works fine for me – Krishna Shrestha Aug 28 '11 at 12:09