Compare two objects with “” operators in Java

You cannot do operator overloading in Java. This means you are not able to define custom behaviors for operators such as +, >, <, ==, etc. in your own classes.

As you already noted, implementing Comparable and using the compareTo() method is probably the way to go in this case.

Another option is to create a Comparator (see the docs), specially if it doesn’t make sense for the class to implement Comparable or if you need to compare objects from the same class in different ways.

To improve the code readability you could use compareTo() together with custom methods that may look more natural. For example:

boolean isGreaterThan(MyObject<T> that) {
    return this.compareTo(that) > 0;
}

boolean isLessThan(MyObject<T> that) {
    return this.compareTo(that) < 0;
}

Then you could use them like this:

if (obj1.isGreaterThan(obj2)) {
    // do something
}

Leave a Comment