Compare two objects with "<" or ">" operators in Java
Asked Answered
M

4

26

How to make two objects in Java comparable using "<" or ">" e.g.

MyObject<String> obj1= new MyObject<String>(“blablabla”, 25);
MyObject<String> obj2= new MyObject<String>(“nannaanana”, 17);
if (obj1 > obj2) 
    do something. 

I've made MyObject class header as

public class MyObject<T extends Comparable<T>> implements Comparable<MyObject<T>> and created method Comp but all the gain I got is now I can use "sort" on the list of objects, but how can I compare two objects to each other directly? Is

if(obj1.compareTo(obj2) > 0)
     do something

the only way?

Multidisciplinary answered 21/3, 2015 at 4:18 Comment(6)
"Is [compareTo] the only way?" Yep.Luster
You cannot overload < or > operators in Java.Aristaeus
In C# you can overload operators like that.Clarke
You can't compare with > & < because there might exist more than one variable in your object and Java won't know which variable you want to use for comparison. If you do not override the compareTo method, it will compare the string object in lexical order.Thackeray
Well, compareTo isn't the only way--you could define isLessThan, isGreaterThan, etc. methods if you want, that return boolean. It's arguable that they'd be more readable than compareTo.Squalid
#78218Electret
D
28

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
}
Devitrify answered 21/3, 2015 at 4:25 Comment(0)
C
4

I would advocated that readability must be a primer for us as developers.

Apache Commons Lang (commons-lang) provides a simple fluent utility which reads a lot clearer:

if (is(obj1).greaterThan(obj2)) {
     // do something
}

Note: is is shorthand for ComparableUtils.is which can be imported the following this static import statement:

import static org.apache.commons.lang3.compare.ComparableUtils.is;
Carapace answered 18/11, 2021 at 15:17 Comment(1)
reason: no instance(s) of type variable(s) A exist so that Object conforms to Comparable<A>Twedy
T
3

Using Comparable.compareTo(T) is the only option (or Comparator). The interface only defines that one method (while Comparator adds equals), and it compares this object with the specified object for order. Further, Java does not permit operator overloading (so you won't be able to directly change the operand used for invoking that method; or in fact modify the interface).

Toreutics answered 21/3, 2015 at 4:25 Comment(3)
There's also Comparator.Aquifer
@Aquifer Comparator provides two methods (and still doesn't allow operator overloading), but that's a fair point in that it is technically another option.Toreutics
I was merely looking at it from the "other option" angle. :)Aquifer
T
3

It is not the only way. You can implement a Comparator as well. Comparator uses compare() method as oppose to Comparable which uses compareTo() method.

The reason you can't use > or < to compare objects directly is because Java won't know which variable you want to use for the comparison (as there might exist more than one variable in the object).

In order to compare objects, those objects must be comparable. You need to define and tell Java how you want to compare them.

Java collection provides a sort method. However some school does give assignment of asking you to write you own sort methods which ultimately still uses the compareTo() for comparison.

You can take a look on the subtle differences between Comparable vs Comparator here: What is the difference between compare() and compareTo()?


I think it is also worth mentioning that, by default Java compares String (objects) in a lexicographical order if you did not override the compareTo() method.

Thackeray answered 21/3, 2015 at 4:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.