Java 在泛型中存在有界通配符问题

Java 在泛型中存在有界通配符问题,java,generics,collections,Java,Generics,Collections,我是Java泛型新手,目前正在试验泛型编码……最终目标是将旧的非泛型遗留代码转换为泛型代码 我用IS-A定义了两个类,即一个是另一个的子类 public class Parent { private String name; public Parent(String name) { super(); this.name = name; } } public class Child extends Parent{ private S

我是Java泛型新手,目前正在试验泛型编码……最终目标是将旧的非泛型遗留代码转换为泛型代码

我用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

为了实现同样的目的,要创建一个可以容纳父类的所有子类的列表,只需将其声明为List myList=new ArrayList

编辑:


为了回答您的另一个困惑,在类型上写入并解释其原因是非法的。

以下是编译错误的原因:

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,它是每种类型的成员


另一方面,给定一个列表<?>/列表<?扩展父级>,我们只能调用get并使用结果。

myList.addnew Parentname;//编译器错误这不起作用,因为您声明了子项列表,但添加了父项。。在您的案例中,不具备成为子地址所需的特定特征。另外,@sanbhat在下面的回答解决了您的问题。为列表声明的结尾无效表示歉意。我已经改正了我的答案
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