I'd like to remove all "unchecked" warnings from this general utility method (part of a larger class with a number of similar methods). In a pinch, I can use @SuppressWarnings("unchecked") but I'm wondering if I can use generics properly to avoid the warning.
The method is intended to be allow callers to compare two objects by passing through to compareTo, with the exception that if the object is a strings it does it in a case insensitive manner.
public static int compareObject(Comparable o1, Comparable o2)
{
if ((o1 instanceof String) && (o2 instanceof String))
return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase());
else
return o1.compareTo(o2);
}
This was my first (incorrect) attempt at a solution. The parameters work fine, but the line o1.compareTo(o2) has a compile error "The method compareTo(capture#15-of ?) in the type Comparable is not applicable for the arguments (Comparable".
public static int compareObject(Comparable<?> o1, Comparable<?> o2)
{
if ((o1 instanceof String) && (o2 instanceof String))
return ((String) o1).toUpperCase().compareTo(((String) o2).toUpperCase());
else
return o1.compareTo(o2);
}
Any suggestions?