我有兴趣使用一个可以处理String
或Integer
数据类型的通用Java类。我想使用比较运算符,但它似乎有一个编译错误:
操作符& lt;不能用于通用
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
和许多其他类实现。