Java Generics MergeSort,线程中的异常" main" java.lang.ClassCastException错误

时间:2014-05-22 09:18:34

标签: java generics mergesort

我使用java泛型为MergeSort编写了一个java程序。但是我得到了以下错误,我不明白我哪里出错了。请帮帮我

线程中的异常" main" java.lang.ClassCastException:[Ljava.lang.Object;无法转换为[Ljava.lang.Comparable;     在src.MergeSort.sort(MergeSort.java:9)     在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));
      }
    }

1 个答案:

答案 0 :(得分:3)

长话短说,这是因为您的类型参数实际上已被删除为Comparable

请记住,泛型会将删除为其边界类型。在大多数情况下,如果没有边界类型,则类型参数将被删除为Object,但在此处,因为您T ComparableT限制,Comparable将被删除到T[] firstHalf = (T[]) new Object[arr.length/2]; 。因此,演员如下:

Comparable[] firstHalf = (Comparable[]) new Object[arr.length / 2];

成为

Object

因为Comparable没有实现Comparable[],所以演员在运行时失败。

解决方案?只需制作阵列{{1}}即可。然后你的演员阵容不会在运行时失败。