如何处理接受字符串或整数的通用 Java 类的比较运算符

2022-01-25 00:00:00 compare java comparator generics

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

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:

运算符 <不能用于通用 T

Operator < cannot be used on generic T

对于T,如何使用比较运算符(如<、>、= 等)?(假设 TNumberString).

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");
        }
    }
}

推荐答案

使用可比界面:

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");
    }
}

StringIntegerLongDoubleDate实现和许多其他课程.

It's implemented by String, Integer, Long, Double, Date and many other classes.

相关文章