Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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");
        }
    }
}
like image 370
code Avatar asked Mar 16 '23 01:03

code


1 Answers

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.

like image 86
Tagir Valeev Avatar answered Apr 26 '23 15:04

Tagir Valeev