Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does this mean Collection<? extends E> c

Tags:

java

javadoc

Some times, well a lot of times I see this thing occurring in the documentation. It leaves me wondering what to type. Could someone explain to me the meaning of this in clear dumbed down text :D. How this:

ArrayList(Collection<? extends E> c)

end up to be used as this:

new ArrayList<>(Arrays.asList("a","b","c"));

so I don't need to ask this "question" anymore by googling it, but being able to figure it out by myself.

like image 551
Josephus87 Avatar asked Nov 05 '15 21:11

Josephus87


1 Answers

The syntax ? extends E means "some type that either is E or a subtype of E". The ? is a wildcard.

The code Arrays.asList("a","b","c") is inferred to return a List<String>, and new ArrayList<> uses the diamond operator, so that yields an ArrayList<String>.

The wildcard allows you to infer a subtype -- you could assign it to a reference variable with a supertype:

List<CharSequence> list = new ArrayList<>(Arrays.asList("a","b","c"));

Here, E is inferred as CharSequence instead of String, but that works, because String is a subtype of CharSequence.

like image 121
rgettman Avatar answered Sep 23 '22 22:09

rgettman