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.