如何处理接受String或Integer的泛型Java类的比较运算符



我有兴趣使用一个可以处理StringInteger数据类型的通用Java类。我想使用比较运算符,但它似乎有一个编译错误:

操作符& lt;不能用于通用T

我如何才能实现使用比较操作符,如<,>, =等T ?(假设TNumberString)。

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和许多其他类实现。

最新更新