Home » Android » How can I convert String[] to ArrayList<String> [duplicate]

How can I convert String[] to ArrayList<String> [duplicate]

Posted by: admin November 30, 2017 Leave a comment

Questions:

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.

Answers:

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

Questions:
Answers:

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);

Questions:
Answers:
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.

Questions:
Answers:

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.

Questions:
Answers:
List myList = new ArrayList();
Collections.addAll(myList, filesOrig); 

Questions:
Answers:

You can do something like

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