I would like to resolve this compiler warning:
unchecked call to compareTo(T) as member of the raw type java.lang.Comparable
My goal is to compare two java.lang.Object
objects of unknown (background) type using following method.
public static boolean Compare(Object o1, Object o2) {
//check if both classes are the same
if(!o1.getClass().equals(o2.getClass())) {
return false;
}
if(Comparable.class.isAssignableFrom(o1.getClass())
&& Comparable.class.isAssignableFrom(o2.getClass())) {
//only if both objects implement comparable
return Comparable.class.cast(o1).compareTo(Comparable.class.cast(o2)) == 0;
}
//other comparison techniques...
}
I know that the problem is that the method casts both objects to Comparable
(Comparable<Object>
), but Object
does not implements Comparable
.
The code itself works, but the compiler throws a warning when using its -Xlint:unchecked parameter.
Goals:
- remove the compiler warning
- keep out of other 'unchecked' warnings
- avoiding using @SupressWarning
- keep Compare method non-generic