Search code examples
javagenericsobjectcastingcomparable

how to send Object to method as comparable parameter?


I have this provided function that I want to use:

boolean check(Comparable<Object> obj1, Comparable<Object> obj2) {
   // do something
}

and I have:

Object obj1,obj2;

that I want to send to method check, how can I cast or convert the two Objects to Comparables ?

I wish I was clear, thank you.


Solution

  • Well, if your two object references are truly pointing to Comparable objects, you could simply do

    check((Comparable<Object>) obj1, (Comparable<Object>) obj2);
    

    -EDIT-

    Of course this generates a warning, you are basically telling the compiler that you know better. The compiler is warning you that there is chance you could be wrong if obj is not truly what you said it was in terms of its generic type parameter. You can tell your compiler to shut up, that you are really, really sure, using an annotation:

    @SuppressWarnings("unchecked")
    Comparable<Object> cmp1 = (Comparable<Object>) obj;
    @SuppressWarnings("unchecked")
    Comparable<Object> cmp2 = (Comparable<Object>) obj;     
    check(cmp1,cmp2);
    

    When you use a @SupressWarning annotation you typically add a comment indicating why you are so positively sure that the unsafe cast will always succeed.