来自Cay Horstmann的Javagenerics,Core Java 7,第I卷,第716页

我正在学习Java 7generics,阅读Cay Horstmann,Core Java7,第I卷,第716页。我不明白为什么会出现运行时错误(非法播放),请参阅下面的代码。 任何人都能比Cay更好地向我解释吗?

public class ProcessArgs { public static  T[] minmax(T... a) { Object[] mm = new Object[2]; mm[0] = a[0]; mm[1] = a[1]; if (mm[0] instanceof Comparable) { System.out.println("Comparable"); // this is True, prints Comparable at run-time } return (T[]) mm; // run-time error here /* Run-Time ERROR as below: ComparableException in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable; at ProcessArgs.minmax(ProcessArgs.java:13) at ProcessArgs.main(ProcessArgs.java:18) */ } public static void main(String[] args) { String[] sa = minmax("Hello","World"); // ERROR, illegal cast System.out.println(sa[0] + sa[1]); Object o = "Hello World"; //works - if we comment out the method call to minmax above Comparable s = (Comparable) o; // works Comparable s2 = (Comparable) o; // works System.out.println(s + " " + (String) s2); // works return; } } 

它会抛出一个错误,因为你创建的实际类型, Object[]不是一个Comparable 。 Javagenerics与数组的处理非常差,如果可能的话,你应该尝试使用Collections。 对于这种情况,您可以使用reflection创建正确类型的数组:

 T[] mm = (T[]) Array.newInstance(a[0].getClass(), 2 ); 

鉴于这两行:

 Object o = "Hello World"; //works - if we comment out the method call to minmax above Comparable s = (Comparable) o; // works 

第二行有效,因为字符串"Hello World"实际上是Comparable

但是Object[]不是,它的类型是Object[] ,所以它不能被强制转换。

只是为了给你提示,你可以比较下面的代码,并了解该代码中发生的事情。

 Object[] mm = new Object[2]; // reference type Object array and object type object array. mm[0] = a[0]; // putting String value into 0th position, so it is comparable, // but whole array is of type Object, so it is not able to cast it to String array while returning. Object o = "Hello World"; // reference type Object and object type String Object o = new String("Hello World"); // this code is also similar to above line. 

注意: String是可比较的,但不是Object数组。