Suppose I have a method called foo taking 2 Object as parameter. Both objects are of the same type and both implements comparable interface.
void foo(Object first, Object second){
if (!first.getClass().isInstance(second)) //first and second of the same type
return;
Comparable firstComparable = (Comparable)first; //WARNING
Comparable secondComparable = (Comparable)second; //WARNING
int diff = firstComparable.compareTo(secondComparable); //WARNING
}
The first 2 warning are:
Comparable is a raw type. References to generic type Comparable should be parameterized
The last warning:
Type safety: The method compareTo(Object) belongs to the raw type Comparable. References to generic type Comparable should be parameterized
How could I refactor my code in order to remove these warnings?
EDIT: Can I do that without changing foo method's signature?
You have to tell the compiler that they are the same type and comparable. If you can't change the signature you can add a method for backward compatibility.
@SuppressWarnings("unchecked")
static void foo(Object first, Object second) {
foo((Comparable) first, (Comparable) second);
}
static <T extends Comparable<T>> void foo(T first, T second){
int diff = first.compareTo(second); // no warning.
}