Reputation: 1378
I wrote a java program for MergeSort using java generics. However I get following errors, I don't understand where I have gone wrong. please Help me out
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable; at src.MergeSort.sort(MergeSort.java:9) at src.MergeSort.main(MergeSort.java:57)
package src; import java.util.Arrays;
public class MergeSort {
// sort array of type T using the Mergesort algorithm
public static <T extends Comparable<T>> T[] sort(T[] arr) {
if (arr.length > 1){
T[] firstHalf = (T[]) new Object[arr.length/2];
System.arraycopy(arr, 0, firstHalf, 0, arr.length /2);
sort(firstHalf);
int secondHalfLength = arr.length -arr.length/2;
T[] secondHalf = (T[]) new Object[secondHalfLength];
System.arraycopy(arr, arr.length/2, secondHalf, 0, secondHalfLength);
sort(secondHalf);
merge(firstHalf, secondHalf, arr);
}
return arr;
}
public static <T extends Comparable<T>> void merge(T[] arr1, T[] arr2, T[] temp) {
int current1 = 0;
int current2 = 0;
int current3 = 0;
while(current1 < arr1.length && current2 < arr2.length){
if (arr1[current1].compareTo(arr2[current2]) < 0)
temp[current3++] = arr1[current1++];
else
temp[current3++] = arr2[current2++];
}
while (current1 < arr1.length)
temp[current3++] = arr1[current1++];
while (current2 < arr2.length)
temp[current3++] = arr2[current2++];
}
public static void main(String[] args) {
// sort list of Characters
Character[] charArr = {'H','e','l','l','o',' ','w','o','r','l','d','!'};
charArr = MergeSort.<Character>sort(charArr);
System.out.println(Arrays.toString(charArr));
// sort list of Integers
Integer[] intArr = {23,4,15,8,42,16};
intArr = MergeSort.<Integer>sort(intArr);
System.out.println(Arrays.toString(intArr));
}
}
Upvotes: 1
Views: 411
Reputation: 11877
Long story short, it's because your type parameter is actually being erased to Comparable
.
Remember, generics are erased to their bounding type. In most cases, where there is no bounding type, type parameters would be erased to Object
, but here, because you're bounding T
by Comparable
, T
is erased to Comparable
. Thus, casts like this:
T[] firstHalf = (T[]) new Object[arr.length/2];
Become
Comparable[] firstHalf = (Comparable[]) new Object[arr.length / 2];
And because Object
doesn't implement Comparable
, the cast fails at runtime.
The solution? Simply make your arrays Comparable[]
. Then your cast won't fail at runtime.
Upvotes: 4