简体   繁体   English

泛型不执行类型擦除

[英]Generics not performing Type Erasure

Following code is throwing java.lang.ArrayStoreException exception. 以下代码抛出了java.lang.ArrayStoreException异常。 To my understanding compiler should generate error or warning as I am using generics . 据我所知,编译器应该生成错误或警告,因为我正在使用generics

Please check the code below and find the commented line. 请检查下面的代码并找到注释行。

   public class Test1 {
        public static void main(String[] args) {
            Collection<Number> nums = new ArrayList<Number>();
            nums.add(new Integer(1));
            nums.add(new Long(-1));
            //every thing is fine here
            Number[] aa = nums.toArray(new Number[0]);
            for (Number num : aa) {
                System.out.println(num);
            }
            // Even if generics are there,no warning or error is reported by complier
            Integer[] bb= nums.toArray(new Integer[nums.size()]);
            for (Integer integer : bb) {
                System.out.println(integer);
            }

        }

    }

Kindly help me understand this behavior. 请帮助我理解这种行为。 Can you please help me understand how to fix this as well? 你能帮我理解如何解决这个问题吗?

The Collection.toArray() method is defined as: Collection.toArray()方法定义为:

<T> T[] toArray(T[] a);

meaning that the type parameter T only binds the parameter type to the return value's type. 意味着类型参数T仅将参数类型绑定到返回值的类型。 It s independent of any type parameters of the enclosing class ( E for element type in the case of Collection ). 它独立于封闭类的任何类型参数(对于Collection的情况, E表示元素类型)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM