Create ArrayList from array
Solution 1:
new ArrayList<>(Arrays.asList(array));
Solution 2:
Given:
Element[] array = new Element[] { new Element(1), new Element(2), new Element(3) };
The simplest answer is to do:
List<Element> list = Arrays.asList(array);
This will work fine. But some caveats:
- The list returned from asList has fixed size. So, if you want to be able to add or remove elements from the returned list in your code, you'll need to wrap it in a new
ArrayList
. Otherwise you'll get anUnsupportedOperationException
. - The list returned from
asList()
is backed by the original array. If you modify the original array, the list will be modified as well. This may be surprising.