本文介绍了用“<"比较两个对象或“>"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>实现 Comparable并创建了 Comp 方法,但我现在获得的所有收益都是我可以在对象列表上使用排序",但是如何直接比较两个对象?是

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.

正如您已经注意到的,在这种情况下,实现 Comparable 并使用 compareTo() 方法可能是可行的方法.

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

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

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
}

这篇关于用“<"比较两个对象或“>"Java 中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 11:37