How to handle comparison operator for Generic Java class accepting String or Integer

♀尐吖头ヾ 提交于 2021-02-07 07:52:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!