How can I convert String[] to ArrayList<String>
191,324
Solution 1
You can do the following:
String [] strings = new String [] {"1", "2" };
List<String> stringList = new ArrayList<String>(Arrays.asList(strings)); //new ArrayList is only needed if you absolutely need an ArrayList
Solution 2
Like this :
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));
or
List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);
Solution 3
List<String> list = Arrays.asList(array);
The list returned will be backed by the array, it acts like a bridge, so it will be fixed-size.
Solution 4
List myList = new ArrayList();
Collections.addAll(myList, filesOrig);
Solution 5
You can loop all of the array and add into ArrayList:
ArrayList<String> files = new ArrayList<String>(filesOrig.length);
for(String file: filesOrig) {
files.add(file);
}
Or use Arrays.asList(T... a)
to do as the comment posted.
Author by
Alexandre Hitchcox
Updated on November 08, 2020Comments
-
Alexandre Hitchcox over 3 years
Possible Duplicate:
Assigning an array to an ArrayList in JavaI need to convert a
String[]
to anArrayList<String>
and I don't know howFile dir = new File(Environment.getExternalStorageDirectory() + "/dir/"); String[] filesOrig = dir.list();
Basically I would like to transform
filesOrig
into anArrayList
. -
zapl about 12 years
...new ArrayList<String>(filesOrig.length);
prevents that the backing array has to be grown in size. Potentially faster. -
Alexandre Hitchcox about 12 yearsThanks, this is the one I used
-
MysticMagicϡ over 9 yearsThanks.. I couldn't use
Arrays.asList
as I had to add element to list later.addAll
worked perfectly :) -
Bob Lissner over 7 yearsI don't believe that you can then make changes to this list. stringList.remove(1) sure isn't working for me.
-
suriv over 7 yearsThis answer is wrong and won't even compile.
-
Jack over 7 years@suriv: the only problem was
List
instead ofArrayList
but the answer is not wrong. Creating a copy of an array to anArrayList
is not always necessary, sometimes you just need to view an array as a list. Mind that creating a real copy, as innew ArrayList<>(Arrays.asList(array))
requires a memory for each element of the list. For example a 100000Object
array requires 800kb of RAM just for the pointers to references. -
suriv over 7 yearsFor the benefit of future readers, trying to add or remove elements from this List will throw an exception.
-
Jack over 7 years@suriv: it's clearly stated in the answer and it's clearly stated in the documentation, in any case thanks for the clarification.
-
Someone Somewhere almost 6 yearssecond option works