I have the following inline Comparator.
private static class SampleSorter implements Comparator<SampleClass>{
public int compare(SampleClass o1, SampleClass o2) {
if (o1 instanceof Comparable) {
return ((Comparable) o1).compareTo(o2);
} else if (o2 instanceof Comparable) {
return -((Comparable) o2).compareTo(o1);
}
return 0;
}
}
Which generates the following warnings:
Comparableis a raw type. References to generic typeComparable<T>should be parameterized
And if I instead parameterize the types as suggested:
if (o1 instanceof Comparable) {
return ((Comparable<SampleClass>) o1).compareTo(o2);
Then I get warnings…
Type safety: Unchecked cast from
SampleClasstoComparable<SampleClass>
And if I do typechecking:
if (o1 instanceof Comparable<SampleClass>) {
return ((Comparable<SampleClass>)o1).compareTo (o2);
I get the following error:
Cannot perform instanceof check against type
Comparable<SampleClass>. Use the formComparable<?>instead since generic type information will be erased at runtime
And again, if I follow the advice of the error message:
if (o1 instanceof Comparable<?>) {
return ((Comparable<?>)o1).compareTo (o2);
I get this error:
The method
compareTo(capture#4-of ?)in the typeComparable<capture#4-of ?>is not applicable for the arguments(SampleClass)
Now I don’t know how to procede, I really prefere code which is warning- and error-free.
How do I produce warning-free code with the wanted behaviour?
The problem you have is there is no way for the compiler to know that what you are doing is safe. Instead you have to trust you know what you are doing and you can add this annotation
tot he method or the class and the warning go away.