In the following code, the method isSorted
causes my static code analyzer to give me a warning saying:
Unchecked call to 'compareTo(T)' as a member of raw type 'java.lang.comparable'
Now, I found from other posts that the solution is to generify the function as done in the equivalent function isSortedG
.
However, I do not understand why the second method is better than the first. As far as I can tell, since isSorted
takes a Comparable[]
as argument, this should result in a compile time check of any usage of that function to make sure that the input array is indeed of a type that implements Comparable
.
In other words, what is this 'Unchecked call' that the static checker is warning about?
public class SortChecker{
public boolean isSorted(Comparable[] arr){
if(arr.length == 1){
return true;
}
for(int i = 1; i < arr.length; ++i){
if(arr[i].compareTo(arr[i-1]) < 0){
return false;
}
}
return true;
}
public <T extends Comparable<? super T>> boolean isSortedG(T[] arr){
if(arr.length == 1){
return true;
}
for(int i = 1; i < arr.length; ++i){
if(arr[i].compareTo(arr[i-1]) < 0){
return false;
}
}
return true;
}
}