Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cannot add String to type to List<?>?

Tags:

java

generics

The error:

The method add(capture#1-of ?) in the type List<capture#1-of ?> is not 
applicable for the arguments (String)

Code:

List<?> to = new ArrayList<Object>();
to.add(new String("here"));

Since List<?> is a generic type List and therefore can be of any type, then why it is not accepting String in add method?

like image 317
blue-sky Avatar asked Sep 05 '13 10:09

blue-sky


4 Answers

A List<?> is a list of some type, which is unknown. So you can't add anything to it except null without breaking the type-safety of the list:

List<Integer> intList = new ArrayList<>();
List<?> unknownTypeList = intList;
unknownTypeList.add("hello"); // doesn't compile, now you should see why
like image 138
JB Nizet Avatar answered Oct 16 '22 19:10

JB Nizet


should a String not be acceptable ?

No. <?> means the type is unknown and the compiler cannot be sure that any type is acceptable to add (this include String)

like image 41
Peter Lawrey Avatar answered Oct 16 '22 19:10

Peter Lawrey


You can specify a lower bound:

List<? super Object> to = new ArrayList<Object>();
to.add(new String("here")); // This compiles

Now the compiler is sure that the list can contain any Object

like image 2
ZhekaKozlov Avatar answered Oct 16 '22 18:10

ZhekaKozlov


According to wildcards, the question mark (?), called the wildcard, represents an unknown type and not a generic type, since its an unknown type the compiler cannot accept String in your case.

like image 1
Sajan Chandran Avatar answered Oct 16 '22 18:10

Sajan Chandran