Reputation: 904
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.
Upvotes: 0
Views: 2038
Reputation: 78589
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.
Upvotes: 3
Reputation: 4171
Objects you want to send to this method must be type of Comparable
. So they must implement Comparable
interface.
Comparable obj1 = new Comparable() {
// ... realize compare method
}
then you can send this object to your function.
If you have your own class implement interface this way:
public class MyClass implements Comparable {
// realize compare method
}
Upvotes: 0
Reputation: 691765
As you said:
check((Comparable<Object>) obj1, (Comparable<Object>) obj2);
That said, I don't know of any class that implements Comparable<Object>
. The method should probably take Comparable<?>
as arguments rather than Comparable<Object>
.
Upvotes: 4
Reputation: 285405
Don't use
Object obj1, obj2;
but rather
Comparable obj1, obj2;
Upvotes: 2