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)};

And you would like to convert this to an ArrayList:

ArrayList<Element> arraylist = ???;

..then you can do the following!

The solution

The technique

new ArrayList<>(Arrays.asList(array));

How to use it

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

List<ClassName> list = Arrays.asList(array)

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));