Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array that is initialised 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 = ???;

I am sure I have done this before, but the solution is sitting just at the edge of my memory.

share|improve this question
132  
+1 for being the first hit on google when searching for "java construct arraylist from array". Thanks! – Greg Hewgill Oct 8 '09 at 22:45

7 Answers

up vote 828 down vote accepted
new ArrayList<Element>(Arrays.asList(array))
share|improve this answer
66  
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
18  
@Luron - just use List<ClassName> list = Arrays.asList(array) – Pool Jun 29 '11 at 15:18
50  
@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
19  
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 at 3:28
9  
@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 at 9:41
show 9 more comments

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|improve this answer
29  
+1 for the UnsupportedOperationException caveat. – Senthil Kumar May 1 '12 at 10:17
What is the time complexity of both operations? I mean with and without using explicit arraylist construction. – damned May 23 '12 at 2:17
1  
Arrays.asList() merely creates an ArrayList by wrapping the existing array so it is O(1). – Alex Miller May 23 '12 at 13:15
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
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

Since this question is pretty old, it suprises 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 explicit.

share|improve this answer
2  
Thanks Tim; good point. I have up-voted this but will retain the other accepted answer as the question was specifically about the conversion of an array to a List. – Ron Tuffin Jun 22 '11 at 13:47
4  
Fair enough. Maybe that helps someone else. – Tim Büthe Jun 27 '11 at 8:00
thanks ,good point – sergionni Apr 19 at 14:28
new ArrayList<T>(Arrays.asList(myArray));
share|improve this answer
34  
you need to type faster ;) – Tom Oct 1 '08 at 14:41
11  
I was just thinking the same thing! :) – Bill the Lizard Oct 1 '08 at 14:42
2  
This one is actually more correct (Tom's is missing the type annotation) :) – Calum Oct 1 '08 at 14:42
1  
you're right, I updated my answer – Tom Oct 1 '08 at 14:44
11  
and again you should type faster :) – Tom Oct 1 '08 at 14:46
show 2 more comments

(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|improve this answer
4  
+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 at 2:54
@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 at 0:14
@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 at 13:41
@afsantos: ah ah, you're perfectly right indeed. That's what happens when you type stuff on the web without checking it :). Don't know why others rejected your edit, it was correct. Thanks. – haylem May 16 at 15:55

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

Collections.addAll(arraylist, array);
share|improve this answer
This way lets you have a mutable arraylist, though, thanks! – rogerdpack Dec 3 '12 at 20:38

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

List<Element> arraylist = Arrays.asList(array);
share|improve this answer
2  
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
7  
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
You can cast the List<Element> item to an ArrayList<Element> – monksy Oct 9 '09 at 22:48
6  
@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
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 at 9:23

protected by Robert Harvey May 11 '11 at 3:26

This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.

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