This question already has an answer here:
- Create ArrayList from array 33 answers
I'm having a lot of trouble turning an array into an ArrayList
in Java. This is my array right now:
Card[] hand = new Card[2];
"hand" holds an array of "Cards". How this would look like as an ArrayList
?
This will give you a list.
If you want an arraylist, you can do
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 itsof()
andcopyOf()
factory methods (elements can't be null):For A Mutable List
Use the
Lists
class and itsnewArrayList()
factory methods: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.asList()
andCollections.unmodifiableList()
factory methods:Note that:
asList()
saysArrayList
, but it's notjava.util.ArrayList
. It's an inner type, which mimicksArrayList
but actually directly references the past array and forbids some modifications.unmodifiableList()
further locks down changes to the returned view of the original list.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
:For Educational Purposes: The Good ol' Manual Way
declaring the list (and initializing it with an empty arraylist)
adding an element:
iterating over elements:
As an
ArrayList
that line would beTo use the
ArrayList
you have doAlso read this http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html