Compile-time error when using a template in a list

List<? extends String> list = new Arraylist<String>(); list.add("foo"); 

This piece of code gives me compilation time. I do not understand why I cannot add a line to the list. but the code means that we can add an object of class String and its derived class object in the list still I get an error why

+5
source share
3 answers

List<?> Should be used only when you are not interested in the data type of the elements and are interested in operations such as getting the size of the list, etc.

For instance,

 public int getSize(List<?> itemList) { return itemList.size(); } 

This is more of a Read Only list.

You should use the following if you intend to create a new list of String elements.

 List<String> list = new Arraylist<>(); list.add("foo"); 

Alternatively you can use this:

 List<Object> list = new Arraylist<>(); list.add("foo"); 
+2
source

This will work:

 List<? super String> list = new ArrayList<String>(); list.add("foo"); 

Then your compiler will now, so that the caller must pass a list of String objects or a super type.

When do you say <? extends String> <? extends String> , this means that it can be of any type that extends to String . This means that someone can go through the List and they will accept it.

See also here: Difference for <? super / extends String> in the description of methods and variables

+1
source

Essentially List<? extends String> List<? extends String> is a list of an unknown type, all that is known is that this type extends String. It does not matter that the variable contains an instance of List<String> .

Now String is final, so there is no subclass ... so consider:

 List<? extends A> list = new ArrayList<A>(); 

where A is a class with a subclass of B When using a variable of type List<? extends A> List<? extends A> may be an instance of List<B> . We cannot add A to it, because there is a possibility that A not B

But do you know that will be right? Well, the compiler is not , and it does not expect logical connections between an unknown type and what you created, because in the general case you can change this variable at runtime.

A similar example exists in a textbook optimistically called More Fun with Wildcards , where the method accepts (Set<T>, T) , and an invalid call is used using (Set<?>, String) , although the variable Set<?> Contains an instance of Set<String> . The problem is here, despite the addition of extends .

+1
source

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


All Articles