How to Convert an Array to ArrayList in java with Example

I have already shared the difference between Array and ArrayList in java. Also in the last tutorial I have shared the two methods of converting an ArrayList to Array in java with example. In this tutorial I am sharing the two different ways of converting Array to ArrayList.

Method 1 : Using Arrays.asList() method

Syntax :
ArrayList arraylist = new ArrayList(Arrays.asList(arrayname));



import java.util.*;

 class ConvertArrayToArrayList {
    public static void main(String args[]) {
          
          /* Array Declaration and initialization*/
   String citynames[]={"Boston", "Dallas", "New York", "Chicago"};

   /*Array to ArrayList conversion*/
   ArrayList<String> citylist= new ArrayList<String>(Arrays.asList(citynames));

   /*Adding new elements to the converted List*/
   citylist.add("San Francisco");
   citylist.add("San jose");

   /*Final ArrayList content display using for loop*/
   for (String str: citylist)
   {
  System.out.println(str);
          }
  }
} 


Output

Boston
Dallas
New York
Chicago
San Francisco
San jose

Method 2 : Using Collections.addAll() method

 This method does the same as Arrays.asList() method however it is much faster hence performance wise this is a best way to convert Array to ArrayList.


import java.util.*;

 class ConvertArrayToArrayList {
    public static void main(String args[]) {
        
            /* Array Declaration and initialization*/
     String array[]={"AA", "BB", "CC", "DD"};

     /*ArrayList declaration*/
     ArrayList<String> arraylist= new ArrayList<String>();

     /*Conversion*/
     Collections.addAll(arraylist, array);

     /*Adding new elements to the converted List*/
     arraylist.add("Boston");
     arraylist.add("Dallas");

     /*Display array list*/
     for (String str: arraylist)
     {
   System.out.println(str);
     }
  }
}


Output
AA
BB
CC
DD
Boston
Dallas





About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry