简体   繁体   中英

How do I write my own comparison operator in Java?

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, ie 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?

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) .

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
     }
}

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.

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

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

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

}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM