问题描述
假设一个超类美国和它的两个子类SouthAmerica和NorthAmerica
Suppose a SuperClass America and two of its SubClasses SouthAmerica and NorthAmerica
案例1
America[] am = new SouthAmerica[10]; //why no compiler error
am[0]= new NorthAmerica(); //ArrayStoreException at RunTime
案例2
While in Genrics:
While in Genrics:
ArrayList<America> ame = new ArrayList<SouthAmerica>(); //this does not compile
$ b $ p我的问题不是为什么情况2不编译,但我的问题是为什么case 1 compiles.I是什么别的可以做这个基础数组类型和子数组对象?
My question is not why case 2 does not compile but my question is why case 1 compiles.I mean what else can be do this base Array Type and Sub Array Object??
推荐答案
这是因为数组。
数组的行为在很大程度上被认为是
That behavior for arrays is largely considered a mistake:
String[] strings = new String[1];
Object[] objects = strings;
objects[0] = new Integer(1); // RUN-TIME FAILURE
通用集合 - 更新,修正错误。
Generic collections - being newer, fixed that mistake.
您可以使用有界通配符符号< ;? super America>
:
You can use bounded wildcard notation <? super America>
:
ArrayList<? super America> = new ArrayList<SouthAmerica>();
这将允许您将项添加到列表中,避免有问题的行为。
This will allow you to add items to the list, but it will avoid the problematic behavior.
请参阅,了解如何使用它们。
See this official tutorial on how to use them.
这篇关于Java数组与泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!