Reputation: 15
why this declaration
List<String> ls = new ArrayList<>(new ArrayList<>(new ArrayList<>(Arrays.asList("A"))));
does not give me a nested ArrayList back? What i get is a list with one element ("A") inside.
Upvotes: 0
Views: 18203
Reputation: 73558
There's a constructor ArrayList(Collection<? extends E> c)
, which creates an ArrayList
based on the elements in the collection, so you can call new ArrayList(Arrays.asList("A"));
to create an ArrayList
with the single element "A"
in it (this code can sometimes be seen when a mutable list with initial values is required, as Arrays.asList()
cannot change size).
However the way you're adding new layers of new ArrayList(
on top of that will call the same constructor, taking the elements from the collection and putting them into a single arraylist, instead of nesting them. So you can't use that constructor for creating nested lists.
Your code is equivalent to the following, and as you can see it will always stay just a list of Strings
List<String> ls = new ArrayList<>(Arrays.asList("A"));
ls = new ArrayList<>(ls);
ls = new ArrayList<>(ls);
Upvotes: 1
Reputation: 471
This should do it
List<List<String>> parent = new ArrayList<>();
// Initialize child array
List<String> child = new ArrayList<>();
child.add("one");
child.add("two");
parent.add(child);
Upvotes: 1