Search code examples
javacomparablecompareto

Generic Comparable type for compareTo


I have a method called getMember which may return any Comparable object, String, Integer etc. I can't figure out what to use as type parameter so compareTo will work. Code below is not working

Comparable<? extends Comparable<?>> m1 = column.getMember(o1);
Comparable<? extends Comparable<?>> m2 = column.getMember(o2);

int compareTo = m1.compareTo(m2);

In case I wasn't clear, m1 and m2 will always be same type. Comparing without type parameters works fine, I just wanted to know what to put in <>


Solution

  • I think what you need here is a generic method. Whatever method this section of code is in must be generified. Here's my best shot, in absence of your source for the getMember method.

    public <T extends Comparable<? super T>> void doSomethingTheOPWants() {
        ...
        T m1 = column.getMember(o1);
        T m2 = column.getMember(o2);
        int compareTo = m1.compareTo(m2);
    }
    

    With my current knowledge of the code, I don't think I can create a relevant/worthwhile test, so I'll leave that up to OP.