views:

30929

answers:

4

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.

+65  A: 
new ArrayList<Element>(Arrays.asList(array))
Tom
Duh. Thanks Tom I knew I had seen it someplace (I even had the API docs open on the Arrays class, but was blind to the first method).
Ron Tuffin
Yep. And in the (most common) case where you just want a list, the `new ArrayList` call is unecessary as well.
Calum
how do you access the new arraylist if there is no name for it?
Luron
+6  A: 
new ArrayList<T>(Arrays.asList(myArray));
Bill the Lizard
you need to type faster ;)
Tom
I was just thinking the same thing! :)
Bill the Lizard
This one is actually more correct (Tom's is missing the type annotation) :)
Calum
you're right, I updated my answer
Tom
He can edit his to include it.
Bill the Lizard
and again you should type faster :)
Tom
+3  A: 

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

List<Element> arraylist = Arrays.asList(array);
Kip
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
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
You can cast the List<Element> item to an ArrayList<Element>
monksy
@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
+12  A: 

The simplest answer is to do:

Element[] array = new Element[] { new Element(1),new Element(2),new Element(3) };
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.
Alex Miller