Categories
arraylist arrays java type-conversion

Create ArrayList from array

3976

Given an array of type Element[]:

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

How do I convert this array into an object of type ArrayList<Element>?

ArrayList<Element> arrayList = ???;

0

    4984

    new ArrayList<>(Arrays.asList(array));
    

    10

    • 396

      Yep. And in the (most common) case where you just want a list, the new ArrayList call is unecessary as well.

      – Calum

      Oct 1, 2008 at 14:41

    • 159

      @Luron – just use List<ClassName> list = Arrays.asList(array)

      – Pool

      Jun 29, 2011 at 15:18

    • 272

      @Calum and @Pool – as noted below in Alex Miller’s answer, using Arrays.asList(array) without passing it into a new ArrayList object will fix the size of the list. One of the more common reasons to use an ArrayList is to be able to dynamically change its size, and your suggestion would prevent this.

      Sep 26, 2011 at 19:04


    • 146

      Arrays.asList() is a horrible function, and you should never just use its return value as is. It breaks the List template, so always use it in the form indicated here, even if it does seem redundant. Good answer.

      – Adam

      Jan 23, 2013 at 3:28

    • 87

      @Adam Please study the javadoc for java.util.List. The contract for add allows them to throw an UnsupportedOperationException. docs.oracle.com/javase/7/docs/api/java/util/… Admittedly, from an object-oriented perspective it is not very nice that many times you have to know the concrete implementation in order to use a collection – this was a pragmatic design choice in order to keep the framework simple.

      – lbalazscs

      Feb 22, 2013 at 9:41


    985

    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:

    1. The list returned from asList has fixed size. So, if you want to be able to add or remove elements from the returned list in your code, you’ll need to wrap it in a new ArrayList. Otherwise you’ll get an UnsupportedOperationException.
    2. The list returned from asList() is backed by the original array. If you modify the original array, the list will be modified as well. This may be surprising.

    3

    • 42

      Arrays.asList() merely creates an ArrayList by wrapping the existing array so it is O(1).

      May 23, 2012 at 13:15

    • 33

      Wrapping in a new ArrayList() will cause all elements of the fixed size list to be iterated and added to the new ArrayList so is O(n).

      May 23, 2012 at 13:21

    • To clarify, Arrays.asList() creates a java.util.Arrays.ArrayList (static nested class in java.util.Arrays), not a java.util.ArrayList.

      Feb 15 at 11:24

    385

    (old thread, but just 2 cents as none mention Guava or other libs and some other details)

    If You Can, Use Guava

    It’s worth pointing out the Guava way, which greatly simplifies these shenanigans:

    Usage

    For an Immutable List

    Use the ImmutableList class and its of() and copyOf() factory methods (elements can’t be null):

    List<String> il = ImmutableList.of("string", "elements");  // from varargs
    List<String> il = ImmutableList.copyOf(aStringArray);      // from array
    

    For A Mutable List

    Use the Lists class and its newArrayList() factory methods:

    List<String> l1 = Lists.newArrayList(anotherListOrCollection);    // from collection
    List<String> l2 = Lists.newArrayList(aStringArray);               // from array
    List<String> l3 = Lists.newArrayList("or", "string", "elements"); // from varargs
    

    Please also note the similar methods for other data structures in other classes, for instance in Sets.

    Why Guava?

    The main attraction could be to reduce the clutter due to generics for type-safety, as the use of the Guava factory methods allow the types to be inferred most of the time. However, this argument holds less water since Java 7 arrived with the new diamond operator.

    But it’s not the only reason (and Java 7 isn’t everywhere yet): the shorthand syntax is also very handy, and the methods initializers, as seen above, allow to write more expressive code. You do in one Guava call what takes 2 with the current Java Collections.


    If You Can’t…

    For an Immutable List

    Use the JDK’s Arrays class and its asList() factory method, wrapped with a Collections.unmodifiableList():

    List<String> l1 = Collections.unmodifiableList(Arrays.asList(anArrayOfElements));
    List<String> l2 = Collections.unmodifiableList(Arrays.asList("element1", "element2"));
    

    Note that the returned type for asList() is a List using a concrete ArrayList implementation, but it is NOT java.util.ArrayList. It’s an inner type, which emulates an ArrayList but actually directly references the passed array and makes it “write through” (modifications are reflected in the array).

    It forbids modifications through some of the List API’s methods by way of simply extending an AbstractList (so, adding or removing elements is unsupported), however it allows calls to set() to override elements. Thus this list isn’t truly immutable and a call to asList() should be wrapped with Collections.unmodifiableList().

    See the next step if you need a mutable list.

    For a Mutable List

    Same as above, but wrapped with an actual java.util.ArrayList:

    List<String> l1  = new ArrayList<String>(Arrays.asList(array));    // Java 1.5 to 1.6
    List<String> l1b = new ArrayList<>(Arrays.asList(array));          // Java 1.7+
    List<String> l2  = new ArrayList<String>(Arrays.asList("a", "b")); // Java 1.5 to 1.6
    List<String> l2b = new ArrayList<>(Arrays.asList("a", "b"));       // Java 1.7+
    

    For Educational Purposes: The Good ol’ Manual Way

    // for Java 1.5+
    static <T> List<T> arrayToList(final T[] array) {
      final List<T> l = new ArrayList<T>(array.length);
    
      for (final T s : array) {
        l.add(s);
      }
      return (l);
    }
    
    // for Java < 1.5 (no generics, no compile-time type-safety, boo!)
    static List arrayToList(final Object[] array) {
      final List l = new ArrayList(array.length);
    
      for (int i = 0; i < array.length; i++) {
        l.add(array[i]);
      }
      return (l);
    }
    

    1

    • 31

      +1 But note that the List returned by Arrays.asList is mutable in that you can still set elements – it just isn’t resizable. For immutable lists without Guava you might mention Collections.unmodifiableList.

      Jan 10, 2013 at 2:54