2

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;
    }
}
Community
  • 1
  • 1
balajeerc
  • 3,998
  • 7
  • 35
  • 51

1 Answers1

2

A nongeneric Comparable "can" be compared to any Object (as per its compareTo() signature), but in actuality, there may only be a small set of types to which it can be meaningfully compared (and giving it other types will cause compareTo() to throw an exception). For example, you can cast an Integer to a Comparable, but that still won't let you compare it to a String. Therefore, a Comparable[] is risky business, because you have no idea which elements are safe to compare and which are not. The generic version is safer because a Comparable<T> usually is comparable to any T, and if T is constrained to implementors of Comparable<? super T>, all elements of a T[] should be mutually comparable.

Aasmund Eldhuset
  • 37,289
  • 4
  • 68
  • 81