List<? extends String> list = new Arraylist<String>();
list.add("foo");
Given piece of code gives me compile time error.i don't get it why i can't add string in list. but the code means that we can add the String class object and it's derived class object in the list still i am getting the error why
List<?>
should only be used when you are not concerned with the data type of the items and interested in operations such as getting size of list etc.
For Example,
public int getSize(List<?> itemList) {
return itemList.size();
}
It is more of a Read Only
list.
You should be using the following if you intend to make a new list of String
items.
List<String> list = new Arraylist<>();
list.add("foo");
Alternatively, you can use this:
List<Object> list = new Arraylist<>();
list.add("foo");
This will work:
List<? super String> list = new ArrayList<String>();
list.add("foo");
Then your compiler will now, that the caller is to pass a list of objects that are String
or a super type.
When you say <? extends String>
it means it can be of any type which extends String
. That means somebody can pass List
and it will accept it.
Look also here: Difference for <? super/extends String> in method and variable declaration
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With