Integer
, for instance, implements Comparable
, so it's legal to write:
Comparable[] list = new Comparable[3];
list[0] = Integer.valueOf(3);
list[1] = Integer.valueOf(2);
list[2] = Integer.valueOf(3);
You can see all the implementors of Comparable
in the standard JDK by looking at the JavaDoc.
The trouble is (and you should see some compiler warnings about this), you can't both specify the generic parameter for Comparable
and make an array of the parameterized object, that is, it's not legal to write:
Comparable<Integer>[] list = new Comparable<Integer>[3];
Even if it were legal to write that, you'd run into a new issue, since you need the concrete type to use in the Comparable<T>
test. Comparable<T>
requires a comparison to an object of type T
(the method is int compareTo(T o)
). In essence, your code only works because it's unparameterized (T
is implicitly Object
, everything extends Object
), but you're losing some compile-time safety checks along the way.
It might make more sense to parameterize your input by an array of generic parameterized Comparable
objects rather than as an array of Comparable
. Writing this using generics is a little bit tricky, the method prototype would look something like:
public static void <T extends Comparable<T>> selectionSort(T[] list) {
// legal to call list[k].compareTo, because `T` is guaranteed to be `Comparable`
}
Notably, this will work for any non-primitive object type T
that implements Comparable<T>
, such as an Integer[]
or Double[]
, but not an int[]
.