143

Possible Duplicate:
Assigning an array to an ArrayList in Java

I need to convert a String[] to an ArrayList<String> and I don't know how

File dir = new File(Environment.getExternalStorageDirectory() + "/dir/");
String[] filesOrig = dir.list();

Basically I would like to transform filesOrig into an ArrayList.

Alexandre Hitchcox
  • 2,704
  • 5
  • 22
  • 33

6 Answers6

366

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
Scott
  • 9,458
  • 7
  • 54
  • 81
41

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);
EricParis16
  • 809
  • 5
  • 9
19
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.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • This answer is wrong and won't even compile. – suriv Jan 24 '17 at 12:26
  • @suriv: the only problem was `List` instead of `ArrayList` but the answer is not wrong. Creating a copy of an array to an `ArrayList` is not always necessary, sometimes you just need to view an array as a list. Mind that creating a real copy, as in `new ArrayList<>(Arrays.asList(array))` requires a memory for each element of the list. For example a 100000 `Object` array requires 800kb of RAM just for the pointers to references. – Jack Jan 24 '17 at 13:59
  • 1
    For the benefit of future readers, trying to add or remove elements from this List will throw an exception. – suriv Jan 24 '17 at 15:10
  • 1
    @suriv: it's clearly stated in the answer and it's clearly stated in the documentation, in any case thanks for the clarification. – Jack Jan 24 '17 at 15:14
9
List myList = new ArrayList();
Collections.addAll(myList, filesOrig); 
sarwar026
  • 3,821
  • 3
  • 26
  • 37
7

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.

Pau Kiat Wee
  • 9,485
  • 42
  • 40
  • 1
    `...new ArrayList(filesOrig.length);` prevents that the backing array has to be grown in size. Potentially faster. – zapl Apr 19 '12 at 15:07
2

You can do something like

MyClass[] arr = myList.toArray(new MyClass[myList.size()]);

Carlos Tasada
  • 4,438
  • 1
  • 23
  • 26