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
2010-09-19 17:10:32
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
2010-09-19 17:15:43
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
2010-09-19 17:39:54
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
2010-09-19 17:47:25
+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
2010-09-19 17:11:28