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
You probably just need a List, not an ArrayList. In that case you can just do:
List<Element> arraylist = Arrays.asList(array);
You also can do it with stream in Java 8.
List<Element> elements = Arrays.stream(array).collect(Collectors.toList());
If the array is of a primitive type, the given answers won't work. But since Java 8 you can use:
int[] array = new int[5];
Arrays.stream(array).boxed().collect(Collectors.toList());
Even though there are many perfectly written answers to this question, I will add my inputs.
Say you have Element[] array = { new Element(1), new Element(2), new Element(3) };
New ArrayList can be created in the following ways
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) }));
// Add through a collection
ArrayList<Element> arraylist_3 = new ArrayList<>();
Collections.addAll(arraylist_3, array);
And they very well support all operations of ArrayList
arraylist_1.add(new Element(4)); // or remove(): Success
arraylist_2.add(new Element(4)); // or remove(): Success
arraylist_3.add(new Element(4)); // or remove(): Success
But the following operations returns just a List view of an ArrayList and not actual ArrayList.
// Returns a List view of array and not actual ArrayList
List<Element> listView_1 = (List<Element>) Arrays.asList(array);
List<Element> listView_2 = Arrays.asList(array);
List<Element> listView_3 = Arrays.asList(new Element(1), new Element(2), new Element(3));
Therefore, they will give error when trying to make some ArrayList operations
listView_1.add(new Element(4)); // Error
listView_2.add(new Element(4)); // Error
listView_3.add(new Element(4)); // Error
More on List representation of array link.
In Java 9, you can use List.of static factory method in order to create a List
literal. Something like the following:
List<Element> elements = List.of(new Element(1), new Element(2), new Element(3));
This would return an immutable list containing three elements. If you want a mutable list, pass that list to the ArrayList
constructor:
new ArrayList<>(List.of(// elements vararg))
JEP 269 provides some convenience factory methods for Java Collections API. These immutable static factory methods are built into the List, Set, and Map interfaces in Java 9 and later.
// Guava
import com.google.common.collect.ListsLists
...
List<String> list = Lists.newArrayList(aStringArray);