问题
I am interested in using a generic Java class which can handle String
or Integer
data type. I'd like to utilize the comparison operator, but it appears to have a compile error:
Operator < cannot be used on generic
T
How can I achieve using comparison operators such as <, >, =, etc. for T
? (Assuming T
is Number
or 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");
}
}
}
回答1:
Use Comparable interface:
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");
}
}
It's implemented by String
, Integer
, Long
, Double
, Date
and many other classes.
来源:https://stackoverflow.com/questions/32086894/how-to-handle-comparison-operator-for-generic-java-class-accepting-string-or-int