I'm trying to implement a generic MergeSort sorting algorithm. the function only accepts the type that implements Comparable interface as well as display function takes an array of any type to display the content of the array. But I'm receiving this exception -
Exception in thread "main" java.lang.ClassCastException: java.base/[Ljava.lang.Comparable; cannot be cast to java.base/[Ljava.lang.Integer;
at mergeSort.MergeSort.main(MergeSort.java:10)
My code is below:
package mergeSort;
import java.util.Arrays;
public class MergeSort
{
public static void main(String[] args)
{
Integer[] array = new Integer[]{3, 4, 2, 9, 5, 7, 8, 1, 6};
display(mergeSort(array));
}
public static <T extends Comparable<T>> T[] mergeSort(T[] array)
{
if(array.length <= 1) return array;
int leftLength = array.length/2;
int rightLength = array.length - leftLength;
T[] left = (T[]) new Comparable[leftLength];
T[] right = (T[]) new Comparable[rightLength];
for(int i = 0; i < array.length; i++)
{
if(i < leftLength)
{
left[i] = array[i];
}
else
{
right[Math.abs(left.length-i)] = array[i];
}
}
return merge(mergeSort(left), mergeSort(right));
}
public static <T extends Comparable<T>> T[] merge(T[] left, T[] right)
{
T[] merged = (T[]) new Comparable[left.length + right.length];
int i = 0;
int j = 0;
int k = 0;
while(i < left.length && j < right.length)
{
if(left[i].compareTo(right[j]) < 0)
{
merged[k++] = left[i++];
}
else
{
merged[k++] = right[j++];
}
}
while(i < left.length) merged[k++] = left[i++];
while(j < right.length) merged[k++] = right[j++];
return merged;
}
public static <T> void display(T[] array)
{
Arrays.stream(array).forEach(value -> System.out.print(value + " "));
System.out.println();
}
}
Comparable[](array) toInteger[]. This[Lfoo.Bar;is how Java array types are notated in some places.