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
In Java 9
you can use:
List<String> list = List.of("Hello", "World", "from", "Java");
List<Integer> list = List.of(1, 2, 3, 4, 5);
According with the question the answer using java 1.7 is:
ArrayList<Element> arraylist = new ArrayList<Element>(Arrays.<Element>asList(array));
However it's better always use the interface:
List<Element> arraylist = Arrays.<Element>asList(array);
You can convert using different methods
List<Element> list = Arrays.asList(array);
List<Element> list = new ArrayList();
Collections.addAll(list, array);
Arraylist list = new Arraylist();
list.addAll(Arrays.asList(array));
For more detail you can refer to http://javarevisited.blogspot.in/2011/06/converting-array-to-arraylist-in-java.html
Java 8’s Arrays class provides a stream() method which has overloaded versions accepting both primitive arrays and Object arrays.
/**** Converting a Primitive 'int' Array to List ****/
int intArray[] = {1, 2, 3, 4, 5};
List<Integer> integerList1 = Arrays.stream(intArray).boxed().collect(Collectors.toList());
/**** 'IntStream.of' or 'Arrays.stream' Gives The Same Output ****/
List<Integer> integerList2 = IntStream.of(intArray).boxed().collect(Collectors.toList());
/**** Converting an 'Integer' Array to List ****/
Integer integerArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> integerList3 = Arrays.stream(integerArray).collect(Collectors.toList());
Use the following code to convert an element array into an ArrayList.
Element[] array = {new Element(1), new Element(2), new Element(3)};
ArrayList<Element>elementArray=new ArrayList();
for(int i=0;i<array.length;i++) {
elementArray.add(array[i]);
}
Already everyone has provided enough good answer for your problem. Now from the all suggestions, you need to decided which will fit your requirement. There are two types of collection which you need to know. One is unmodified collection and other one collection which will allow you to modify the object later.
So, Here I will give short example for two use cases.
Immutable collection creation :: When you don't want to modify the collection object after creation
List<Element> elementList = Arrays.asList(array)
Mutable collection creation :: When you may want to modify the created collection object after creation.
List<Element> elementList = new ArrayList<Element>(Arrays.asList(array));