Search code examples
javagenericscomparable

Use known methods of generic objects


I'm having a class receiving 2 unknown, generic Objects x and y. I have to compare these to objects if they are comparable. I figured out that I can check if the Objects implements the Comparable interface by using instanceof, but I don't know how I can use the .compareTo method although I know that the Object implements them-

What I want to do is basically this with x and y being generic Objects:

public void someMethod(E x, E y) {
    if (x instanceof Comparable && y instanceof Comparable) {
        if(x.compareTo(y) < 0){    //The method compareTo(E) is undefined for the type E
            //do stuff
        }
    }
}

Could anybody point me in the right direction?


Solution

  • After checking you can (and should) cast the objects safely to use them as you need.

     if (x instanceof Comparable && y instanceof Comparable) {
        Comparable c1 = (Comparable) x;
        Comparable c2 = (Comparable) y;        
        if(c1.compareTo(c2) < 0){
            //do stuff
        }
    }