我想知道如何使用foreach遍历包含混合内容的列表。请参阅下面的示例代码。
public class GenericsForeach {
class A {
void methodA() {
System.out.println(getClass().getSimpleName() + ": A");
}
}
class B extends A {
void methodB() {
System.out.println(getClass().getSimpleName() + ": B");
}
}
void test() {
List<A> listOfA = new ArrayList<A>();
listOfA.add(new A());
List<B> listOfB = new ArrayList<B>();
listOfB.add(new B());
List<? super A> mixed = new ArrayList<A>();
mixed.addAll(listOfA);
mixed.addAll(listOfB);
Iterator<? super A> it = mixed.iterator();
while (it.hasNext()) {
A item = (A) it.next();
item.methodA();
}
// XXX: this does not work
// for (A item : mixed) {
// item.methodA();
// }
}
public static void main(String[] args) {
new GenericsForeach().test();
}
}
我用不同但相关的内容类型构造了两个列表
A
和
B
(
乙
延伸
一
)我将这两个列表添加到一个“混合”列表中,我声明其中包含
<? super A>
类型。因为这个混合列表正在“消耗”类型的项
一
(或)
乙
)我应用了bloch的pecs规则(producer extends,consumer super)来确定我需要
<?超级A和GT;
在这里。
到目前为止,还不错。但现在当我想遍历这个混合列表时,我只能用
Iterator<? super A>
和演员
A item = (A) it.next()
. 当我尝试使用foreach循环(请参阅注释掉的代码)时,没有乐趣:
类型不匹配:无法从元素类型捕获转换8-of?超级通用foreach.a到通用foreach.a
eclipse甚至乐于提供
是否将“项”的类型更改为?超级A
但这会带来灾难:
for (? super A item : mixed) {
item.methodA();
}
所以我不知道。日食似乎不知道。这里还有人知道这是否可能,如果不可能,为什么不知道?