This question already has answers here:
Casting to generic type in Java doesn't raise ClassCastException?
                                
                                    (5个答案)
                                
                        
                                4年前关闭。
            
                    
这个程序...

public static void main(String[] args) {

    String[] table = (String[]) new Object[20];

    table[1] = "bla";

}


...产生强制转换异常:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at tests.App.main(App.java:10)


但是,使用泛型完成的相同操作不会产生任何错误:

public static void main(String[] args) {

    doIt("bla");

}

public static <V>void doIt(V val) {

    V[] table = (V[]) new Object[20];

    table[1] = val;
}


为什么使用泛型有什么不同?

最佳答案

这是因为type erasure。在运行时,V[]只是Object[]

07-26 00:59