Sunday, May 1, 2011

How to convert a String array to ArrayList?

Method 1:

String[] words = {"ace", "boom", "crew", "dog", "eon"};
List<String> wordList = Arrays.asList(words);

Method 2:

List<String> list = new ArrayList<String>(words.length);
for (String s : words) {

Method 3 :

Collections.addAll(myList, myStringArray);

Note: In the method no 1 Arrays.asList() is efficient because it doesn't need to copy the content of the array. This method returns a List that is a "view" onto the array - a wrapper that makes the array look like a list. When you change an element in the list, the element in the original array is also changed. Note that the list is fixed size - if you try to add elements to the list, you'll get an exception.

If you only need read access to the array as if it is a List and you don't want to add or remove elements from the list, then only use method no 1.

No comments:

Post a Comment