[英]Having Issue with Bounded Wildcards in Generic
我是Java Generics的新手,我目前正在尝试Generic Coding。...最终目标是将旧的Non-Generic遗留代码转换为Generic。
我用IS-A定义了两个类,即一个是另一个的子类。
public class Parent {
private String name;
public Parent(String name) {
super();
this.name = name;
}
}
public class Child extends Parent{
private String address;
public Child(String name, String address) {
super(name);
this.address = address;
}
}
现在,我正在尝试创建一个有界通配符的列表。 并得到编译器错误。
List<? extends Parent> myList = new ArrayList<Child>();
myList.add(new Parent("name")); // compiler-error
myList.add(new Child("name", "address")); // compiler-error
myList.add(new Child("name", "address")); // compiler-error
有点困惑。 请帮助我解决这个问题吗?
那是因为您已经创建了ArrayList<Child>
要实现相同目的(即创建一个可以容纳Parent
所有子类的List
),只需将其声明为List<Parent> myList = new ArrayList<Parent>();
List<Parent> myList = new ArrayList<Parent>(); --> new ArrayList should have generic type Parent
myList.add(new Parent("name")); // will work
myList.add(new Child("name", "address")); // will work
myList.add(new Child("name", "address")); // will work
编辑:
为了解决您的其他困惑,在上限通配符类型上写是非法的,下面是一个线程来说明为什么是这样。
这就是编译错误的原因:
List<?> myList2 = new ArrayList<Child>();
myList2.add(new Child("name", "address")); // compiler-error
List<? extends Parent> myList2 = new ArrayList<Child>();
myList1.add(new Child("name", "address")); // compiler-error
由于我们不知道myList2 / myList1的元素类型代表什么,因此无法向其添加对象。 add()方法采用类型E(集合的元素类型)的参数。 当实际类型参数为?时,代表某种未知类型。 我们传递来添加的任何参数都必须是该未知类型的子类型。 由于我们不知道是什么类型,因此无法传递任何内容。唯一的例外是null,它是每种类型的成员。
另一方面,给定一个列表<? > /列表<? 扩展Parent>,我们只能调用get()并利用结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.