【问题标题】:Generic type java.util.List inheritance泛型 java.util.List 继承
【发布时间】:2013-12-24 13:40:11
【问题描述】:

假设我有两个类 PersonChildChild 继承自 Person。我还有 2 个其他类 Class1Class2

Class1 的构造函数只有一个参数 - 它是 Person 的 java.util.ListClass2Child 列表。我想将这些孩子传递给 Class1 构造函数。但我做不到 - Eclipse 这么说

The constructor Class1(List<Child>) is undefined.

我认为这是可能的,因为 Child 继承自 Person。有什么问题?

SSCCE(不可编译)可能如下所示:

Class2 中的某处

List<Child> childs = new ArrayList<Child>();
new Class1(childs);

Class1 构造函数

public Class1(List<Person> persons)
{
//do nothing();
}

【问题讨论】:

  • List 不是 List 的子类

标签: java list generics inheritance


【解决方案1】:

如果 List&lt;Apple&gt;List&lt;Fruit&gt;,您可以执行以下操作:

List<Apple> apples = new ArrayList<>();
List<Fruit> fruits = apples; // this doesn't actually compile
fruits.add(new Banana()); 

因此它会彻底破坏泛型类型的类型安全。如果您希望 Class1 接受任何类型的 Person 列表,它应该采用 List&lt;? extends Person&gt; 作为参数。

【讨论】:

  • 更好的答案,因为有一个解释为什么这是不可能的
【解决方案2】:

如果你以这种方式定义构造函数

public Class1(List<? extends Person> persons) {
}

您将能够将List&lt;Child&gt; 传递给它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-27
    • 2015-09-15
    • 2017-10-28
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多