Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

ArrayList initialization equivalent to array initialization

we can initialize an array during instantiation as follows:

String[] names = new String[] {"Ryan", "Julie", "Bob"};

Is there a way to do the same thing with an ArrayList? Or must it add the contents individually with array.add()?
by

2 Answers

Bharatgxwzm
new ArrayList<String>(){{
add("A");
add("B");
}}

What this is really doing is making a class got from rrayList<String> (the external arrangement of supports do this) and afterwards proclaim a static initialiser (the internal arrangement of supports). This is really an inward class of the containing class, thus it'll have an understood this pointer. Not an issue except if you need to serialize it, or you're anticipating that the outer class should be trash gathered.

Alter: ongoing Java renditions give more usable capacities to making such assortments, and merit exploring over the abovementioned (gave at a time prior to these variants)
Shahlar1vxp
For ArrayList initialization equivalent to array initialization, the following code may be used as answer-
ArrayList<Integer>
(Arrays.asList(1, 2, 3, 5, 8, 13, 21));

But it is important to understand what is this code all about?
Firstly, the elements are copied into the Arrays.ArrayList<I> which gets created by a static factory Arrays.asList(T..). But it does not produce the same class as the java. lang.ArrayList although it has the same class name. Now, the Arrays.ArrayList<I> which was constructed by us is passed to the constructer-
ArrayList<>
(Collection<T>
. Now, the constructer decides whether to copy it again for removing the subclass type. - Arrays.asList(T..) where it internally uses an array of type T.

Login / Signup to Answer the Question.