Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...