8

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.

Josephus87
  • 1,126
  • 9
  • 19
  • 5
    Take a look at the [Oracle Tutorial on Generics](https://docs.oracle.com/javase/tutorial/java/generics/boundedTypeParams.html). You may want to read the whole chapter, since generics in Java can be pretty messy. Also, look up the [PECS Mnemonic](http://stackoverflow.com/questions/2723397/java-generics-what-is-pecs). – Turing85 Nov 05 '15 at 21:13

2 Answers2

14

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357
0
List<String> testList1 = new ArrayList<>(Arrays.asList("a","b","c"));

This statement creates an entirely new ArrayList object that contains the same elements as the list generated using Arrays.asList("a","b","c").

Therefore, the new ArrayList and the original String list are completely independent objects.

FYI : Arrays.asList(arrAgument); This creates a immutable/ unmodifiable list.We cannot be altered by adding or removing items because the underlying String array's length cannot be changed at run time. if you try to do add or remove a java.lang.UnsupportedOperationException will be thrown at run time.

Yuresh Karunanayake
  • 519
  • 1
  • 4
  • 10