类从比较类型转换为整数类型的异常

时间:2019-02-12 16:39:48

标签: java algorithm generics mergesort

我正在尝试实现通用的MergeSort排序算法。该函数仅接受实现Comparable接口的类型,并且display函数采用任何类型的数组来显示该数组的内容。但是我收到了这个例外-

Exception in thread "main" java.lang.ClassCastException: java.base/[Ljava.lang.Comparable; cannot be cast to java.base/[Ljava.lang.Integer;

在mergeSort.MergeSort.main(MergeSort.java:10)

我的代码如下:

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();
    }
}

1 个答案:

答案 0 :(得分:3)

此方法声明承诺不会执行的操作:

public static <T extends Comparable<T>> T[] mergeSort(T[] array)

您没有返回T[]。您将返回Comparable[]。因此,可以这样声明:

public static Comparable<?>[] mergeSort(Comparable<?>[] array) { ... }
public static Comparable<?>[] merge(Comparable<?>[] left, Comparable<?>[] right) { ... }

或者,使用Array.newInstance()创建数组。例如:

public static <T extends Comparable<T>> T[] merge(T[] left, T[] right) {
    T[] merged = (T[]) Array.newInstance(
        left.getClass().getComponentType(), 
        left.length + right.length);
    ...