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

24 Answers 24

up vote 3175 down vote accepted
new ArrayList<Element>(Arrays.asList(array))
share
264  
Yep. And in the (most common) case where you just want a list, the new ArrayList call is unecessary as well. – Calum Oct 1 '08 at 14:41
90  
@Luron - just use List<ClassName> list = Arrays.asList(array) – Pool Jun 29 '11 at 15:18
178  
@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. – Code Jockey Sep 26 '11 at 19:04
90  
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 '13 at 3:28
54  
@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 '13 at 9:41

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.
share
2  
What is the time complexity of both operations? I mean with and without using explicit arraylist construction. – damned May 23 '12 at 2:17
18  
Arrays.asList() merely creates an ArrayList by wrapping the existing array so it is O(1). – Alex Miller May 23 '12 at 13:15
13  
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). – Alex Miller May 23 '12 at 13:21
7  
the implementation of List returned by asList() does not implement several of List's methods (like add(), remove(), clear(), etc...) which explains the UnsupportedOperationException. definitely a caveat... – sethro Nov 14 '12 at 19:33
4  
When the question asks for "an object of the ArrayList class" I think it's reasonable to assume the class it refers to is java.util.ArrayList. Arrays.asList actually returns a java.util.Arrays.ArrayList which is not an instanceof the other class. So a third caveat is that if you try to use it in a context requiring the above it will not work. – Dave L. Jun 24 '16 at 19:16

(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);
}
share
18  
+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. – Paul Bellora Jan 10 '13 at 2:54
1  
@PaulBellora: Thanks Paul, I had never taken the time to update based on your comment, but this is finally done. You'd have been welcome to do it yourself though, as you were perfectly right. Thanks for fixing typos back then as well. – haylem Apr 17 '13 at 0:14
1  
@haylem In your section For Educational Purposes: The Good ol' Manual Way, your arrayToList for Java 1.5+ is incorrect. You are instanciating lists of String, and trying to retrieve strings from the given array, instead of using the generic parameter type, T. Other than that, good answer, and +1 for being the only one including the manual way. – afsantos May 16 '13 at 13:41

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.

share
3  
In particular, List<String> a = Arrays.asList("first","second","third") – 18446744073709551615 Jul 12 '16 at 15:29
new ArrayList<T>(Arrays.asList(myArray));

Make sure that myArray is the same type as T. You'll get a compiler error if you try to create a List<Integer> from an array of int, for example.

share

Another way (although essentially equivalent to the new ArrayList(Arrays.asList(array)) solution performance-wise:

Collections.addAll(arraylist, array);
share

You probably just need a List, not an ArrayList. In that case you can just do:

List<Element> arraylist = Arrays.asList(array);
share
8  
That will be backed by the original input array, which is why you (probably) want to wrap it in a new ArrayList. – Bill the Lizard Oct 1 '08 at 14:46
13  
Be careful with this solution. If you look, Arrays ISN'T returning a true java.util.ArrayList. It's returning an inner class that implements the required methods, but you cannot change the memebers in the list. It's merely a wrapper around an array. – Mikezx6r Oct 1 '08 at 14:47
1  
You can cast the List<Element> item to an ArrayList<Element> – monksy Oct 9 '09 at 22:48
8  
@Mikezx6r: little correction: it's a fixed-size list. You can change the elements of the list (set method), you cannot change the size of the list (not add or remove elements)! – Carlos Heuberger Dec 4 '09 at 13:10
1  
Yes, with the caveat that it depends on what you want to do with the list. It's worth notng that if the OP simply wants to iterate through the elements, the array doesn't have to be converted at all. – PaulMurrayCbr May 5 '13 at 9:23

Another update, almost ending year 2014, you can do it with Java 8 too:

ArrayList<Element> arrayList = Stream.of(myArray).collect(Collectors.toCollection(ArrayList::new));

A few characters would be saved, if this could be just a List

List<Element> list = Stream.of(myArray).collect(Collectors.toList());
share
4  
It's probably best not to be implementation-dependent, but Collectors.toList() actually returns an ArrayList. – bcsb1001 Dec 31 '14 at 19:55
    
incorrect use of Stream.of(...); that will create a one element stream. Use Arrays.stream instead – Patrick Parker Nov 18 '16 at 11:59
    
I don't think so, the 2 options are valid but the Arrays.stream is slightly 'better' since you can create it with fixed size, using the overload method with 'start', 'end' args. See also: stackoverflow.com/a/27888447/2619091 – whyem Nov 30 '16 at 21:45

To convert an array to an ArrayList, developers often do this:

List<String> list = Arrays.asList(arr);// this is wrong way..

Arrays.asList() will return an ArrayList which is a private static class inside Arrays, it is not the java.util.ArrayList class. The java.util.Arrays.ArrayList class has set(), get(), contains() methods, but does not have any methods for adding elements, so its size is fixed. To create a real ArrayList, you must do:

ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(arr));

The constructor of ArrayList can accept a Collection type, which is also a super type for java.util.Arrays.ArrayList

share
4  
It's not the wrong way if you just need a List, and don't need an ArrayList, which you actually don't most of the time. Most of the time when developers create an ArrayList it's out of habit, more than out of need. – Christoffer Hammarström Oct 8 '15 at 11:07
    
Agree with @ChristofferHammarström, both are valid List<String> list = Arrays.asList(arr); is used to create List and ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(arr)); is used to create ArrayList. Probably @Nepster has just copy pasted an extract from programcreek.com/2013/04/… – Nikhil Katre Jan 29 at 6:48

Java 9

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: Convenience Factory Methods for Collections

JEP 269 provides some convenience factory methods for Collections API. This factory methods are not in current Java version, which is 8, but are planned for Java 9 release. You can try out this feature using JDK 9 Early Access.

share

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.

share
1  
I fail to see the fundamental difference between your loop at the end of the answer and the new ArrayList<T>(Arrays.asList(myArray)); part which you discourage to use. Both do quite the same and have the same complexity. – glglgl Feb 22 '15 at 17:03
    
The Collections one create a pointer at the beginning of the array. My loop create many pointers : one for each array member. So if the original array changes, my poiners are still directed toward the former values. – Nicolas Zozol Feb 22 '15 at 19:59
1  
new ArrayList<T>(Arrays.asList(myArray)); does the same, it copies the asList to an ArrayList... – glglgl Feb 22 '15 at 21:56

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);
share
// Guava
import com.google.common.collect.ListsLists
...
List<String> list = Lists.newArrayList(aStringArray); 
share

You can convert using different methods

  1. List<Element> list = Arrays.asList(array);

  2. List<Element> list = new ArrayList();
    Collections.addAll(list, array);

  3. 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

share

You also can do it with stream in Java 8.

 List<Element> elements = Arrays.stream(array).collect(Collectors.toList()); 
share

Another simple way is to add all elements from the array to a new ArrayList using a for-each loop.

ArrayList<Element> list = new ArrayList<>();

for(Element e : array)
    list.add(e);
share
  1. If we see the definition of Arrays.asList() method you will get something like this:

     public static <T> List<T> asList(T... a) //varargs are of T type. 
    

    So, you might initialize arraylist like this:

     List<Element> arraylist = Arrays.asList(new Element(1),new Element(2),new Element(3));
    

    Note : each new Element(int args) will be treated as Individual Object and can be passed as a var-args.

  2. There might be another answer for this question too.
    If you see declaration for java.util.Collections.addAll() method you will get something like this:

    public static <T> boolean addAll(Collection<? super T> c, T... a);
    

    So, this code is also useful to do so

    Collections.addAll(arraylist, array);
    
share

Since Java 8 there is easier way to transform:

public static <T> List<T> get(T[] array) {
    return Arrays.stream(array).collect(toList());
}
share

and the common newest way to create array is observableArrays

thus the answer is

FXCollections.observableArrayList(new Element(1), new Element(2), new Element(3));

that is according to Oracle Docs

observableArrayList() Creates a new empty observable list that is backed by an arraylist. observableArrayList(E... items) Creates a new observable array list with items added to it.

share

Arrays.asList(yourArray) method is used to convert your array into arrayList

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

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.

share

If your Array is of type String,

String str[] = { "a", "b" ,"c" ,"d" ,"e" };  
List<String> list = new ArrayList<String>(Arrays.asList(str));

To learn more about ArrayList , refer this link

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

ArrayList<Element> arraylist =  new ArrayList<Element>(Arrays.asList(array));
for (Element sample : array){
    arraylist.add(sample);
    System.out.println("Your Element in ArrayList" + sample);
}

Quick way to Convert Array to ArrayList is to use Array.asList() Method

share

There is another option if your goal is to generate a fixed list at runtime, which is as simple as it is effective:

static final ArrayList<Element> myList = generateMyList();

private static ArrayList<Element> generateMyList() {
  final ArrayList<Element> result = new ArrayList<>();
  result.add(new Element(1));
  result.add(new Element(2));
  result.add(new Element(3));
  result.add(new Element(4));
  return result;
}


The benefit of using this pattern is, that the list is for once generated very intuitively and therefore is very easy to modify even with large lists or complex initialization, while on the other hand always contains the same Elements on every actual run of the program (unless you change it at a later point of course).

share
6  
This doesn't answer the original question. The OP already has the elements in a container, which we can assume has random contents. This approach depends on the list needing the exact same elements every time this code is run. Also, the overuse of the static keyword is bad practice, and there are many other ways of doing this in practice which involve less boilerplate code. – Shotgun Ninja Apr 8 '15 at 15:17

protected by Jorgesys Nov 23 '16 at 19:10

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.