Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two objects with "<" or ">" operators in Java

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?

like image 232
IvanN Avatar asked Mar 21 '15 04:03

IvanN


People also ask

Can we compare 2 objects in Java?

In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity.

How do you compare two sets of objects in Java?

The equals() method of java. util. Set class is used to verify the equality of an Object with a Set and compare them. The method returns true if the size of both the sets are equal and both contain the same elements.

What is difference between == equals () and compareTo () method?

The equals() tells the equality of two strings whereas the compareTo() method tell how strings are compared lexicographically.

What happens when you compare two string objects with the == operator what is Java actually comparing?

In Java, "==" compares the object identity. "new" is guaranteed to return a new object identity each time.


1 Answers

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
}
like image 129
Anderson Vieira Avatar answered Oct 05 '22 11:10

Anderson Vieira