将两个对象与“<”进行比较或“>” Java中的运算符 [英] Compare two objects with "<" or ">" operators in Java

查看:305
本文介绍了将两个对象与“<”进行比较或“>” Java中的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用<使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. 

我已将MyObject类标题设为

I've made MyObject class header as

public class MyObject< T extends Comparable< T>>实现Comparable< MyObject< T>>
和创建的方法Comp但是我获得的所有增益现在我可以在对象列表上使用sort,但我怎么能比较两个直接对象?

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

唯一的方法?

推荐答案

您无法在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您已经注意到,实现 Comparable 并使用 compareTo()方法可能就是这种情况。

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

另一种选择是创建比较器(参见 docs ),特别是如果对类实现没有意义可比较或者如果您需要以不同方式比较同一类中的对象。

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.

为了提高代码可读性,您可以使用 compareTo()以及可能看起来更自然的自定义方法。例如:

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
}

这篇关于将两个对象与“&lt;”进行比较或“&gt;” Java中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆