Initialize an ArrayList Using asList()

Unlike arrays, we cannot initialize array lists directly. However, we can use the asList() method of the Arrays class to achieve the same effect. In order to use the asList() method, we must import the java.util.Arrays package first.

For example,


\begin{lstlisting}
import java.util.ArrayList;
import java.util.Arrays;
\par
cla...
...1);
System.out.println(''Accessed Element: '' + element);
}
}
\end{lstlisting}

Output


\begin{lstlisting}
ArrayList: [Cat, Cow, Dog]
Accessed Elemenet: Cow
\end{lstlisting}

In the above example, notice the expression,


\begin{lstlisting}
new ArrayList<>(Arrays.asList((''Cat'', ''Cow'', ''Dog''));
\end{lstlisting}

Here, we have first created an array of 3 elements: "Cat", "Cow", and "Dog". Then, the asList() method is used to convert the array into an array list.