Convert String Array to Arraylist

I was working on collections in one of my project and while working on copying arrays to collections found below two approaches to do it. These two approaches have their advantages as well as limitations.



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

public class StringArrayToCollectionSample
{
   public static void main(String[] args)
   {
      String[] strArray = new String[] {"Hello", "World", "Application"};
      List<String> strList = Arrays.asList(strArray);


   }
}

This approach will work fine 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. As it doesn't need to copy the content of the array. This method returns a List that is a "view" onto the array or you can say a wrapper that makes the array look like a list.Most important is that the list is of fixed size, i.e if you try to add elements to the list, you'll get an java.lang.UnsupportedOperationException.

Solution 2:
public class StringArrayToCollectionSample
{
   public static void main(String[] args)
   {
      String[] strArray = new String[] {"Hello", "World", "Application"};
      List<String> strList = new ArrayList(Arrays.asList(strArray));

   }
}

This approach will copies the content of the array to a new ArrayList. Advantage of this approach is that you can easily add or remove element from the List.

 

 

No comments:

Post a Comment