Is it possible to assign an array to an ArrayList in Java?
4 Answers
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.
2 Comments
Richard Cook
This answer is better than mine!
Jagadish Nallappa
Collections.addAll(theList, anArray); did it for me. Thank you very much! :)
The Arrays class contains an asList method which you can use as follows:
String[] words = ...;
List<String> wordList = Arrays.asList(words);
3 Comments
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.
peakit
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);
Richard Cook
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.
If you are importing or you have an array (of type string) in your code and you have to convert it into arraylist (offcourse string) then use of collections is better. like this:
String array1[] = getIntent().getExtras().getStringArray("key1"); or
String array1[] = ...
then
List<String> allEds = new ArrayList<String>();
Collections.addAll(allEds, array1);