Convert String array to arraylist

Solution 1:
  
import java.util.Arrays;
import java.util.List;

public class StringArrayToArrayList {
 public static void main(String[] args)  
    {  
       String[] stringArray = {"string1", "string2", "string3", "string4", "string5"};  
    
       List ‹String› arrayList = Arrays.asList(stringArray);  
    
       for (String elements : arrayList)  
       {  
          System.out.println(elements);  
       }
       
       //arrayList.add("adding extra element"); will through exception java.lang.UnsupportedOperationException
    }  

}
Solution 2:
  
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class StringArrayToArrayList {
 public static void main(String[] args)  
    {  
       String[] stringArray = {"string1", "string2", "string3", "string4", "string5"};  
    
       List‹String› arrayList = new ArrayList‹String›(Arrays.asList(stringArray));  
    
       for (String elements : arrayList)  
       {  
          System.out.println(elements);  
       }
       
       
       arrayList.add("adding extra element");// will allow to add the element
    }  

}
Solution 3:
  
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class StringArrayToArrayList {
 public static void main(String[] args)  
    {  
       String[] stringArray = {"string1", "string2", "string3", "string4", "string5"};  
    
       List‹String› arrayList = new ArrayList‹String›;
    
       Collections.addAll(arrayList, stringArray); 
       
       for (String elements : arrayList)  
       {  
          System.out.println(elements);  
       }
       
       
       arrayList.add("adding extra element");// will allow to add the element
    }  

}


The first  solution gives a List that is a read only.  Doesn't copy the content of the array, its only reference to string of array. List size is fixed and you can't do any operations(add,remove ..etc) on the list because its read only.  if you try to add/remove elements to the list, 'll get an exception (java.lang.UnsupportedOperationException).
Second and third solutions, create the new collection object (ArrayList) and  copies the content of the array to a List.  This arraylist independent from array and you can do any operation ( add/remove...) on arraylist.

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 First solution. Otherwise use second or third solution.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...