简体   繁体   中英

Java generic wildcard extend

Why can't I add an integer to this type of list, even though Integer extends Number>

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

Have a look at this post on the PECS principle. 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> .

In short, you'll want to use super rather than 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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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