Sac*_*rma 3 java generics reflection collections
假设一个SuperClass America和它的两个SubClasses SouthAmerica和NorthAmerica
情况1
对于数组:
America[] am = new SouthAmerica[10]; //why no compiler error
am[0]= new NorthAmerica(); //ArrayStoreException at RunTime
Run Code Online (Sandbox Code Playgroud)
案例2
在Genrics中:
ArrayList<America> ame = new ArrayList<SouthAmerica>(); //this does not compile
Run Code Online (Sandbox Code Playgroud)
我的问题不是为什么案例2不编译,但我的问题是为什么案例1编译.我的意思是还有什么可以做这个基础数组类型和子数组对象?
Ben*_*aum 13
那是因为数组是协变的.
数组的这种行为在很大程度上被认为是错误:
String[] strings = new String[1];
Object[] objects = strings;
objects[0] = new Integer(1); // RUN-TIME FAILURE
Run Code Online (Sandbox Code Playgroud)
通用集合 - 更新,修复了这个错误.
您可以使用有界通配符表示法<? super America>:
ArrayList<? super America> = new ArrayList<SouthAmerica>();
Run Code Online (Sandbox Code Playgroud)
这将允许您将项添加到列表中,但它将避免有问题的行为.
请参阅此官方教程,了解如何使用它们.