tags:

views:

122

answers:

2

Hello, I was wondering if it is possible to assign an array to an ArrayList in Java.

+4  A: 

The Arrays class contains an asList method which you can use as follows:

String[] words = ...;
List<String> wordList = Arrays.asList(words);
Richard Cook
This returns a fixed-size list of strings encapsulated by some private type that implements the List<String> interface. @NullUserException's answer is the best if you need an instance of java.util.ArrayList that is mutable.
Richard Cook
Richard, just wanted to know that why is the above list becoming fixed-size? Can't I further add another element to the same list in the next line.. like wordList.add(anotherStringElement);
peakit
That's the defined behaviour of the asList method. As @NullUserException points out you should convert to an ArrayList [ArrayList<Type> aList = new ArrayList<Type>(Arrays.asList(words)] in order to obtain an ArrayList that you can add further items to.
Richard Cook
+11  A: 

You can use Arrays.asList():

Type[] anArray = ...
ArrayList<Type> aList = new ArrayList<Type>(Arrays.asList(anArray));

or alternatively, Collections.addAll():

ArrayList<Type> aList = new ArrayList<Type>();
Collections.addAll(theList, anArray); 

Note that you aren't technically assigning an array to a List (well, you can't do that), but I think this is the end result you are looking for.

NullUserException
This answer is better than mine!
Richard Cook
@NullUserException: Your `<Type>` is misplaced.
missingfaktor
@Missing Thanks, fixed
NullUserException