[英]Generic type java.util.List inheritance
Lets say I've got two classes Person and Child . 可以说我有两个班级Person和Child 。 Child inherits from Person . 孩子从Person继承。 I have also 2 other classes Class1 and Class2 . 我也有2个其他类Class1和Class2 。
Class1 has constructor with only one parameter - its a java.util. Class1的构造函数只有一个参数-它是java.util。 List of Person . 人的名单 。 Class2 has List of Child . Class2具有List的Child 。 I want to pass these childs to Class1 constructor. 我想将这些孩子传递给Class1构造函数。 But I can't do it - Eclipse says that 但是我做不到-Eclipse说
The constructor Class1(List<Child>) is undefined.
I thought it would be possible because Child inherits from Person . 我认为这是可能的,因为Child继承自Person 。 What is the problem? 问题是什么?
SSCCE (not compilable) may looks like this: SSCCE(不可编译)可能如下所示:
Somewhere in Class2 Class2的某个地方
List<Child> childs = new ArrayList<Child>();
new Class1(childs);
Class1 constructor Class1构造函数
public Class1(List<Person> persons)
{
//do nothing();
}
If a List<Apple>
was a List<Fruit>
, you could do the following: 如果List<Apple>
是List<Fruit>
,则可以执行以下操作:
List<Apple> apples = new ArrayList<>();
List<Fruit> fruits = apples; // this doesn't actually compile
fruits.add(new Banana());
And it would thus completely break the type-safety of generic types. 因此,它将完全破坏泛型类型的类型安全性。 If you want Class1 to accept a list of any type of Person, it should take a List<? extends Person>
如果要让Class1接受任何类型的Person的List<? extends Person>
,则应使用List<? extends Person>
List<? extends Person>
as argument. List<? extends Person>
作为参数。
If you define a constructor this way 如果您以这种方式定义构造函数
public Class1(List<? extends Person> persons) {
}
you will be able to pass List<Child>
to it 您将能够将List<Child>
传递给它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.