Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Create ArrayList from array in Java

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 = ???;
by

2 Answers

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

The easiest answer is to do:
List<Element> list = Arrays.asList(array);


This will turn out great. Yet, a few provisos:

1. The rundown got back from asList has fixed size. In this way, in the event that you need to have the option to add or eliminate components from the returned list in your code, you'll need to envelop it with another ArrayList. Else you'll get an UnsupportedOperationException.

2. The rundown got back from asList() is supported by the first cluster. On the off chance that you change the first exhibit, the rundown will be adjusted also. This might be amazing.
Shahlar1vxp
There are several ways of creating ArrayList from array in Java-
Suppose we have-
Element[]
array = { new Element(1),
new Element(2), new Element(3)};
, hence, the ArrayList can be created as follows-
ArrayList<Element> arraylist_1 = new ArrayList<>(Arrays.asList(array));
ArrayList<Element> arraylist_2 = new ArrayList<> (Arrays.asList(new Element[] {new Element(1), new Element(2), new Element(3) }));
ArrayList<Element> arraylist_3 = new ArrayList<>();
Collections.addAll(arraylist_3, array);

You may go for one of the simplest ways which is as follows:
String[] Array={"one", "two", "three"};
ArrayList<String> s1 = new ArrayList<String>(Arrays.asList(Array1));

Login / Signup to Answer the Question.