Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create ArrayList from array

I have an array that is initialized like:

Element[] array = {new Element(1), new Element(2), new Element(3)}; 

I would like to convert this array into an object of the ArrayList class.

ArrayList<Element> arraylist = ???; 
like image 884
Ron Tuffin Avatar asked Oct 01 '08 14:10

Ron Tuffin


People also ask

Can you initialize an ArrayList with an array?

To initialize an arraylist in single line statement, get all elements in form of array using Arrays. asList method and pass the array argument to ArrayList constructor. ArrayList<String> names = new ArrayList<String>( Arrays.


2 Answers

new ArrayList<>(Arrays.asList(array)); 
like image 179
Tom Avatar answered Sep 28 '22 03:09

Tom


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:

  1. 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 an UnsupportedOperationException.
  2. 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.
like image 34
Alex Miller Avatar answered Sep 28 '22 05:09

Alex Miller