0

I’ve got a List<MyObject> list

And, I want to make use out of the list.contains() function.

It doesn’t seem to work at the moment, i.e. there are objects in the list that match, but is not being picked up by the comparator operator.

I’m guessing I need to write my own comparison operator in MyObject. What is the way to go about this?

Larry
  • 11,439
  • 15
  • 61
  • 84

5 Answers5

6

You need to override public boolean equals(Object o) because contains uses it:

boolean contains(Object o)

Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).

See How to implement hashCode and equals method for a discussion of simple and correct ways to override equals.

You need to be especially careful to override equals(Object o) and not just implement equals(MyObject o).

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
0

You have to override equals() in MyObject.

public class MyObject
{

     public boolean equals(Object obj)
     {
          if(this == obj)
               return true;
          if((obj == null) || (obj.getClass() != this.getClass()))
               return false;
          // object must be MyObject at this point
          MyObject test = (MyObject) obj;

          // Compare 'this' MyObject to 'test'

     }

     public int hashCode()
     {
          // generate your hash
     }
}
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
  • 1
    And each time you override the equals, you should override the hashcode too as specified in the javadoc ;-) – Cygnusx1 Sep 13 '11 at 17:49
0

You only have to implement your own version of equals and hashcode on MyObject class.

The default equals will not check the attribute you define in a class. That's why you get the wrong result.

Cygnusx1
  • 5,329
  • 2
  • 27
  • 39
0

Your class needs to implement equals(). It's also useful to implement the Comparable interface, if you ever want to sort your objects E.g.

class MyObject implements Comparable<MyObject> {
   public int compareTo(MyObject o) {
       // do the compare!
   }

   public boolean equals(Object o) {
      // check equality
   }

}
TotoroTotoro
  • 17,524
  • 4
  • 45
  • 76
  • Not in his case. He only need to override the equals and hashcode method. This would be the case if he wanted to sort stuff with a SortedSet for example – Cygnusx1 Sep 13 '11 at 17:48
0

Notice the documentation for List's contains method: List.contains()

It states that it used the equals method to determine equality and therefore determine if the element exists in the list.

Also, note that when you overload equals you must overload hashCode.

John B
  • 32,493
  • 6
  • 77
  • 98