我正在学习Java 7泛型,阅读Cay Horstmann,Core Java7,第I卷,第716页.我不明白为什么会出现运行时错误(非法播放),请参阅下面的代码.任何人都能比Cay更好地解释它吗?
public class ProcessArgs
{
public static <T extends Comparable> 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<String> s = (Comparable) o; // works
Comparable s2 = (Comparable) o; // works
System.out.println(s + " " + (String) s2); // works
return;
}
}
Run Code Online (Sandbox Code Playgroud)
它会抛出一个错误,因为你创建的实际类型Object[]不是Comparable.Java泛型与数组的处理非常差,如果可能的话,你应该尝试使用Collections.对于这种情况,您可以使用反射创建正确类型的数组:
T[] mm = (T[]) Array.newInstance(a[0].getClass(), 2 );
Run Code Online (Sandbox Code Playgroud)
鉴于这两行:
Object o = "Hello World"; //works - if we comment out the method call to minmax above
Comparable<String> s = (Comparable) o; // works
Run Code Online (Sandbox Code Playgroud)
第二行有效,因为字符串"Hello World"实际上是一个Comparable.
但Object[]不是,它的类型是Object[],所以它不能被施放.