3

是否可以定义用于自定义对象的 if 语句比较的值?

我有:

公共类元素实现 Comparable {

public int value;
public int[] sequence;
public int length;

public element(){}   

public element(int val){
    this.value = val;
}

@Override
public int compareTo(Object o) {
    return
}

}

我想使用 if 语句如下:

如果(元素1>元素2)..

而不是传统的:

如果 (element1.value > element2.value) ..

我无法使用比较器、toString() 等来完成此操作

4

4 回答 4

6

根据JLS 15.20.1 ,您不能将对象引用与>运算符一起使用;Java 不支持运算符重载。但是使用.Comparator

if (comparator.compare(element1, element2) > 0)  // if (element1 > element2)

如果您的类是Comparable<Element>,即与其他元素相当,也是可能的。

if (element1.compareTo(element2) > 0)  // if (element1 > element2)
于 2013-03-18T21:18:48.337 回答
2

不,这在 Java 中是不可能的。从JLS §15.20.1

数值比较运算符的每个操作数的类型必须是可转换(第 5.1.8 节)为原始数值类型的类型,否则会发生编译时错误。

这在像 Python 这样的语言中是可能的,其中几乎所有运算符都可以重载以使用非标准类。

于 2013-03-18T21:19:17.367 回答
1

Java 不支持这个。您可以改用以下内容:

if (element1.compareTo(element2) > 0) {

}

在你的 compareTo 方法中,这样做:

public int compareTo(YourClassObject o) {
    return (this.value - YourClassObject.value);
}
于 2013-03-18T21:24:16.773 回答
1

Since Java does not provide support for operator overloading, comparing the two objects using a method which performs the required comparision is the best option available.

WrapperClass.compare(object1, object2) > 0 for object1.value > object2.value
WrapperClass.compare(object1, object2) < 0 for object1.value < object2.value
WrapperClass.compare(object1, object2) = 0 for object1.value == object2.value

String is one of the class which provides operator overloading like with the concatenation operator.

String str1 = "This ";
String str2 = "is a string";
str1 + str2 equals "This is a string"
于 2013-03-18T21:29:13.677 回答