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 can do it in java 8 as follows
ArrayList<Element> list = (ArrayList<Element>)Arrays.stream(array).collect(Collectors.toList());
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. new ArrayList<>(Arrays.asList(array));
If you use :
new ArrayList<T>(Arrays.asList(myArray));
you may create and fill two lists ! Filling twice a big list is exactly what you don't want to do because it will create another Object[]
array each time the capacity needs to be extended.
Fortunately the JDK implementation is fast and Arrays.asList(a[])
is very well done. It create a kind of ArrayList named Arrays.ArrayList where the Object[] data points directly to the array.
// in Arrays
@SafeVarargs
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
//still in Arrays, creating a private unseen class
private static class ArrayList<E>
private final E[] a;
ArrayList(E[] array) {
a = array; // you point to the previous array
}
....
}
The dangerous side is that if you change the initial array, you change the List ! Are you sure you want that ? Maybe yes, maybe not.
If not, the most understandable way is to do this :
ArrayList<Element> list = new ArrayList<Element>(myArray.length); // you know the initial capacity
for (Element element : myArray) {
list.add(element);
}
Or as said @glglgl, you can create another independant ArrayList with :
new ArrayList<T>(Arrays.asList(myArray));
I love to use Collections
, Arrays
, or Guava. But if it don't fit, or you don't feel it, just write another inelegant line instead.
Since this question is pretty old, it surprises me that nobody suggested the simplest form yet:
List<Element> arraylist = Arrays.asList(new Element(1), new Element(2), new Element(3));
As of Java 5, Arrays.asList()
takes a varargs parameter and you don't have to construct the array explicitly.
Since Java 8 there is an easier way to transform:
import java.util.List;
import static java.util.stream.Collectors.toList;
public static <T> List<T> fromArray(T[] array) {
return Arrays.stream(array).collect(toList());
}