假设一个超类 America 及其两个子类 South America 和 North America
Case 1
对于数组:
America[] am = new SouthAmerica[10]; //why no compiler error
am[0]= new NorthAmerica(); //ArrayStoreException at RunTime
Case 2
在泛型中:
ArrayList<America> ame = new ArrayList<SouthAmerica>(); //this does not compile
我的问题不是为什么情况 2 不能编译,而是为什么情况 1 可以编译。我的意思是这个基本数组类型和子数组对象还能做什么?
那是因为数组是协变 http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29.
数组的这种行为在很大程度上被认为是mistake: http://c2.com/cgi/wiki?JavaArraysBreakTypeSafety
String[] strings = new String[1];
Object[] objects = strings;
objects[0] = new Integer(1); // RUN-TIME FAILURE
通用集合 - 较新,修复了该错误。
您可以使用有界通配符表示法<? super America>
:
ArrayList<? super America> = new ArrayList<SouthAmerica>();
这将使您能够add列表中的项目,但它会避免有问题的行为。
See 这个官方教程 http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html关于如何使用它们。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)