如何处理通用 Java class 接受字符串或整数的比较运算符
How to handle comparison operator for Generic Java class accepting String or Integer
我有兴趣使用可以处理 String
或 Integer
数据类型的通用 Java class。我想使用比较运算符,但它似乎有一个编译错误:
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
和许多其他类实现。
我有兴趣使用可以处理 String
或 Integer
数据类型的通用 Java class。我想使用比较运算符,但它似乎有一个编译错误:
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
和许多其他类实现。