我想做一个List
可以装两种Object
.我想到的是使用通配符。下面是我的代码。
public class Parent {
//code
}
public class ChildOne extends Parent {
//code
}
public class ChildTwo extends Parent {
//code
}
public class Implementation {
List<? extends Parent> list;
public Implementation() {
list.add(new ChildOne());
list.add(new ChildTwo());
ChildOne co = list.get(0);
ChildTwo ct = list.get(1);
}
}
我不能使用 <? extends Parent>
, 因为我做 add
.
但是,我不能使用 <? super Parent>
要么,因为我做get
.
This question声明:don't use a wildcard when you both get and put.
.
那么,如何在不使用通配符的情况下制作几种对象的列表?
最佳答案
通配符不适用于此用例。你应该简单地做
List<Parent> list = new ArrayList<>();
并转换get
的返回值:
ChildOne co = (ChildOne) list.get(0);
ChildTwo ct = (ChildTwo) list.get(1);
关于java - 如果不能使用通配符,如何列出几种对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30161827/