I have a sorting method that takes an ArrayList<Comparable>, sorts it using the compateTo() method, then returns a sorted ArrayList<Comparable>. Here it is:
public static ArrayList<Comparable> insertionSort(ArrayList<Comparable>
input) {
Comparable temp;
ArrayList<Comparable> result;
result = (ArrayList<Comparable>) input.clone();
if (result.size() > 1) {
for (int k = 1; k < result.size(); k++) {
for (int j = 1; j <= k; j++) {
if (result.get(k - j).compareTo(result.get(k - j + 1)) >0){
temp = result.get(k - j + 1);
result.set(k - j + 1, result.get(k - j));
result.set(k - j, temp);
}
}
}
}
return result;
}
Somewhere else in my program, I define DVD objects that implement the Comparable interface, create a bunch of them, and store them in an ArrayList<DVD> called members. Now, when I try to sort members like this:
members = (ArrayList<DVD>) YaSort.insertionSort(members);
I get the following error: Exception in thread “main” java.lang.ClassCastException: [Ljava.lang.Comparable; cannot be cast to [LDVD;
How do I solve this?
Thanks for your time.
The point of generics is that you shouldn’t need to cast anything reference types. Also, rare types, mixing generic and raw types, is bad. And generally
Listis preferred toArrayList, by convention more than anything else.The start of your method should look something like:
(Actually for maximum performance, probably not from an insertion sort over much data, doing something hacky with arrays is better. BTW: The error you are quoting appears to be from the use of arrays rather the collections.)