简体   繁体   English

Java通用通配符扩展

[英]Java generic wildcard extend

Why can't I add an integer to this type of list, even though Integer extends Number> 为什么即使Integer扩展了Number>,我也不能向该类型的列表添加整数

List<? extends Number> numList = new ArrayList<Integer>(); 
Integer f = 12;
numList.add(f);

Have a look at this post on the PECS principle. 看看这篇关于PECS原理的文章。 Relevant quote: 相关报价:

You want to add things to the collection. 您想将东西添加到集合中。
Then the list is a consumer, so you should use a Collection<? super Thing> 那么列表是一个消费者,因此您应该使用Collection<? super Thing> Collection<? super Thing> . Collection<? super Thing>

In short, you'll want to use super rather than extends : 简而言之,您将要使用super而不是extends

List<? super Number> numList = new ArrayList<>(); 
Integer f = 12;
numList.add(f);

如果要存储任何类型的号码,只需执行以下操作:

List<Number> numList = new ArrayList<Number>();

You need to use super keyword if you want to add elements to list. 如果要向列表中添加元素,则需要使用super关键字。

List<? super Integer> numList = new ArrayList<Integer>(); 

and then do 然后做

 numList.add(10);

That List can be defined as List, List some other type also,In this case Compiler dont allow you to have Integer to be stored into a List: that would create problem in the type-safety features. 该列表可以定义为列表,也可以定义其他类型的列表,在这种情况下,编译器不允许将整数存储到列表中:这会在类型安全功能中造成问题。

if you need You could use this 如果您需要,您可以使用此

List<Number> numList = new ArrayList<Number>();
        Integer f = 100;
        numList.add(f);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM