String array to arraylist



There are some important things to note with the solutions given above:

Garrett's solution, with 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.
import java.util.Arrays;  
import java.util.List;  
import java.util.ArrayList;  
public class StringArrayTest  
{  
   public static void main(String[] args)  
   {  
      String[] words = {"ace", "boom", "crew", "dog", "eon"};  
   
      List<String> wordList = Arrays.asList(words);  
   
      for (String e : wordList)  
      {  
         System.out.println(e);  
      }  
   }  


Ernest's solution: new ArrayList(Arrays.asList(myArray)); copies the content of the array to a new ArrayList. The copy is ofcourse independent of the array, and you can add, remove etc. elements as you like.

new ArrayList(Arrays.asList(myArray));

Janarthan's solution, with Collections.addAll(myList, myStringArray); is essentially the same as Ernest's solution.

import java.util.Collections;

List myList = new ArrayList();
String[] myStringArray = new String[] {"Java", "is", "Cool"};

Collections.addAll(myList, myStringArray);

After this code, 'myList' should contain all the elements from the array.

Best regards,
Janarthan S

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 use Garrett's solution. Otherwise use Ernest's or Janarthan's solution.


Very good analysis and you need to add also that copying the array affects the performance of your code so if performance is an issue then user the Arrays.asList() way

你可能感兴趣的:(ArrayList)