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 = ???;
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.
new ArrayList<>(Arrays.asList(array));
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:
ArrayList
. Otherwise you'll get an UnsupportedOperationException
.asList()
is backed by the original array. If you modify the original array, the list will be modified as well. This may be surprising. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With