Why can't I add a String to a type in List <?>?

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 of List and therefore can be of any type, why doesn't it accept String in the add method?

+6
source share
5 answers

A List<?> Is a list of some type that is unknown. Thus, you cannot add anything to it except zero, without violating the list type security:

 List<Integer> intList = new ArrayList<>(); List<?> unknownTypeList = intList; unknownTypeList.add("hello"); // doesn't compile, now you should see why 
+11
source

should the string be unacceptable?

No. <?> means that the type is unknown, and the compiler cannot be sure that any type is valid for addition (including String).

+6
source

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

+2
source

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

+1
source

You can view any list defined using wildcards as read-only. However, there are some non-read operations you can do.

From the docs :

  • You can add null.
  • You can use clear.
  • You can get an iterator and call delete.
  • You can grab a wildcard and write down the items you read from the list.
0
source

Source: https://habr.com/ru/post/953229/


All Articles