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");
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With