Skip to content

How to create ArrayList from Array in Java

The problem

If you have a traditional array, that looks something like the following:

A[] array = {new A(1), new A(2), new A(3)};
Code language: Java (java)

And you would like to convert this to an ArrayList:

ArrayList<Element> arraylist = ???;
Code language: Java (java)

..then you can do the following!

The solution

The technique

new ArrayList<>(Arrays.asList(array));
Code language: Java (java)

How to use it

Of course you could always simplify this one further directly as:

List<ClassName> list = Arrays.asList(array)
Code language: Java (java)

How to old Java

If you are stuck in the old world of Java, you can fall back to:

List<ClassName> list = new ArrayList<ClassName>(Arrays.asList(array));
Code language: Java (java)

See also  How to Get the Opposite of a Number in Java
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x