Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compile time error while using wildcard in List

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

like image 611
Aman Gupta Avatar asked Sep 25 '22 12:09

Aman Gupta


2 Answers

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");
like image 115
user2004685 Avatar answered Oct 11 '22 14:10

user2004685


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

like image 29
m.aibin Avatar answered Oct 11 '22 14:10

m.aibin