144

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.

2
  • 1
    stackoverflow.com/questions/3746639/… Commented Apr 19, 2012 at 15:01
  • 1
    Ironic that it was labeled as duplicate, even though this is more famous than the original. Commented Aug 12, 2019 at 9:35

6 Answers 6

367

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
Sign up to request clarification or add additional context in comments.

1 Comment

I don't believe that you can then make changes to this list. stringList.remove(1) sure isn't working for me.
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);

2 Comments

Thanks.. I couldn't use Arrays.asList as I had to add element to list later. addAll worked perfectly :)
second option works
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.

4 Comments

This answer is wrong and won't even compile.
@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.
For the benefit of future readers, trying to add or remove elements from this List will throw an exception.
@suriv: it's clearly stated in the answer and it's clearly stated in the documentation, in any case thanks for the clarification.
9
List myList = new ArrayList();
Collections.addAll(myList, filesOrig); 

Comments

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.

1 Comment

...new ArrayList<String>(filesOrig.length); prevents that the backing array has to be grown in size. Potentially faster.
2

You can do something like

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.