In writing a static generic method to do an insertion Sort. I ran across the following wild card capture problem that I cannot solve. There is a simple solution to the problem but I still would like to know why my original attempt does not compile. I have done a similar thing for quicksort which compiles correctly.
Note: I know that by changing the declaration from List<? extends T> col
to List<T> col
the code will compile and run properly. But because I am capturing the wildcard in the "move" method below, it should also compile if I leave the
"? extends T" as is. Does anyone have any idea why it refuses to compile? I am using jdk1.8.0_60 in Eclipse( NEON ).
Here is the relevant code that does not compile:
public static <T extends Comparable<? super T>>
void insertionSort(List<? extends T> col) {
for ( int i = 1 ; i < col.size(); i++ ){
int j = i - 1 ;
T key = col.get(i);
while ( j > -1 && col.get(j).compareTo(key) > 0 ) {
T ele = col.get(j);
InsertionSort.move(j+1,ele,col); // **DOES NOT COMPILE**
j = j - 1;
}
InsertionSort.move(j+1, key, col); // **DOES NOT COMPILE**
}
}
private static <T> void move(int jplus1, T key, List<T> col) {
col.set(jplus1, key);
}
I am doing a similar thing with quickSort which, believe it or not , compiles correctly. Here is the quicksort that actually compiles correctly: Notice the swap method.
public static <T extends Comparable<? super T>>
void quickSort(List<? extends T> col) {
Objects.requireNonNull(col);
_quickSort(col, 0, col.size() - 1);
}
private static <T extends Comparable<? super T>>
void _quickSort(List<? extends T> col, int start, int end) {
int partitionPoint = 0;
if (start < end) {
partitionPoint = partition(col, start, end);
_quickSort(col, start, partitionPoint - 1);
_quickSort(col, partitionPoint + 1, end);
}
}
private static <T extends Comparable<? super T>>
int partition(List<? extends T> col, int start, int end) {
T pivot = col.get(end);
int partitionIndex = start;
for (int j = start; j <= (end - 1); j++) {
int cmp = col.get(j).compareTo(pivot);
if (cmp < 1) {
swap(j, partitionIndex, col); // COMPILES CORRECTLY
partitionIndex++;
}
}
swap(partitionIndex, end, col);
return partitionIndex;
}
private static <T> void swap(int j, int partitionIndex, List<T> col) {
T temp = col.get(j);
col.set(j, col.get(partitionIndex));
col.set(partitionIndex, temp);
}