I have some generics in the following code:
public <T extends Comparable<T>> int insertionSort(T[] a) {
// throw new RuntimeException("not implemented");
final int L = a.length;
int compares = 0;
for(int i = 1; i < L; i++){
for(int j = i; j > 0 && a[j].compareTo(a[j - 1]) < 0; j--){
Comparable tmp = a[j]; // PROBLEM HERE
a[j] = a[j - 1];
a[j - 1] = tmp; // PROBLEM HERE
compares++;
}
}
return compares;
}
// PROBLEM HERE – those two lines in the code have a fault.
The errors are I can’t make the assignments.
Your problem is that
Comparableis an interface, not a class. you need to create an Object of a class that implementsComparable.If
TimplementsComparable, than you can declare tmp as aTand use that: