1. Using Arrays class asList() method
2. Using Collections class addAll() method
3. Using add() method
Convert an Array to ArrayList in Java
Method 1 : Using Arrays.asList() method
In this example, we are converting an Array to ArrayList using Arrays class asList() method. The syntax is given below:
Syntax :
ArrayList<String> list = new ArrayList<>(Arrays.asList(arrayname));
import java.util.*; public class ConvertArrayToArrayList { public static void main(String args[]) { // Declaring and initializing Array String[] cities={"Boston", "Dallas", "New York", "Chicago"}; //Converting Array to ArrayList using Arrays.asList() ArrayList<String> list= new ArrayList<>(Arrays.asList(cities)); // Add more elements to the converted list list.add("San Francisco"); list.add("San jose"); // Print arraylist elements using for-each loop for(String s : list) { System.out.println(s); } } }
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 the best way to convert Array to ArrayList. The syntax for the addAll() method is given below:
Syntax:
Collections.addAll(arraylist, array);
import java.util.*; public class ConvertArrayToArrayList2 { public static void main(String args[]) { // Creating and initializing Array String[] strArray = {"AAA", "BBB", "CCC", "DDD"}; // Declaring ArrayList ArrayList<String> al = new ArrayList<>(); //Converting Array to ArrayList using addAll() method Collections.addAll(al, strArray); // Add more elements to the converted list al.add("YYY"); al.add("ZZZ"); // Displaying arraylist elements using for-each loop for(String s : al) { System.out.println(s); } } }
Output:
AAA
BBB
CCC
DDD
YYY
ZZZ
Method 3 : Using add() method
If we don't want to use java built-in methods then we can use add() method to convert an array to ArrayList. This is a manual way of adding all the array elements to the ArrayList as shown below:
import java.util.*; public class ConvertArrayToArrayList3 { public static void main(String args[]) { // Declaring and instantiating ArrayList in one step ArrayList<String> al = new ArrayList(); // Given initialized array String[] strArray = {"Cocacola", "Pepsi", "Fanta", "Dr Pepper"}; //Converting Array to ArrayList manually for (int i=0; i < strArray.length ; i++) { // Adding every element of array to the ArrayList al.add(strArray[i]); } // Showing arraylist elements using for-each loop for(String str1 : al) { System.out.println(str1); } } }
Output:
Cocacola
Pepsi
Fanta
Dr Pepper
That's all for today. Please mention in the comments if you have any questions related to how to convert an array to ArrayList in Java with examples.