Search code examples
javajavadoc

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


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.


Solution

  • 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.