我对使用可以处理 String
或 Integer
数据类型的通用 Java 类很感兴趣。我想使用比较运算符,但它似乎有一个编译错误:
Operator < cannot be used on generic
T
如何为 T
使用比较运算符,例如 <、>、= 等? (假设 T
是 Number
或 String
)。
public class Node<T> {
public T value;
public Node(){
}
public void testCompare(T anotherValue) {
if(value == anotherValue)
System.out.println("equal");
else if(value < anotherValue)
System.out.println("less");
else if(value > anotherValue)
System.out.println("greater");
}
}
}
最佳答案
使用Comparable
界面:
public class Node<T extends Comparable<T>> {
public T value;
public Node() {
}
public void testCompare(T anotherValue) {
int cmp = value.compareTo(anotherValue);
if (cmp == 0)
System.out.println("equal");
else if (cmp < 0)
System.out.println("less");
else if (cmp > 0)
System.out.println("greater");
}
}
由String
、Integer
、Long
、Double
、Date
实现和许多其他类。
关于java - 如何处理接受字符串或整数的通用 Java 类的比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32086894/