[英]Collection generics unable to add objects of defined type
I have created 2 objects: Person
and Men
(extends Person
). 我创建了2个对象: Person
和Men
(扩展Person
)。 Then I created a generic collection to add only the Men
objects, but for some reason it's not allowing me to add the Men object. 然后,我创建了一个通用集合,仅添加Men
对象,但是由于某种原因,它不允许我添加Men对象。
class Person{
}
class Men extends Person{
}
public class test extends HashSet<Person>{
public static void main(String[] args) {
List<? extends Person> p1 = new ArrayList<Men>();
p1.add(new Men());
}
}
List<? extends Person>
List<? extends Person>
means "a List
of some concrete type that extends Person
, but we don't know what that concrete type actually is". List<? extends Person>
的意思是“一个List
,扩展了一些具体类型的Person
,但我们不知道是什么具体类型实际上是”。 For all we know, it could be a List<Women>
! 就我们所知,它可能是List<Women>
! For this reason, you can't actually add anything to this list (except null
). 因此,您实际上无法在此列表中添加任何内容 ( null
除外)。 You likely want: 您可能想要:
List<Men> p1 = new ArrayList<Men>(); // a list of only Men instances
make it List<? super Men> p1 = new ArrayList<Men>();
使其成为List<? super Men> p1 = new ArrayList<Men>();
List<? super Men> p1 = new ArrayList<Men>();
. 。 You can read about Polymorphism and generics 您可以阅读有关多态和泛型的信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.