Java Program to Convert the Arraylist to an array and vice versa

Java Program to Convert the Arraylist to an array and vice versa

In this example, we will learn to convert the arraylist into an array and vice versa in Java.

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Convert the Arraylist into Array

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {
    ArrayList<String> languages= new ArrayList<>();

    // Add elements in the arraylist
    languages.add("Java");
    languages.add("Python");
    languages.add("JavaScript");
    System.out.println("ArrayList: " + languages);

    // Create a new array of String type
    String[] arr = new String[languages.size()];

    // Convert ArrayList into the string array
    languages.toArray(arr);
    System.out.print("Array: ");
    for(String item:arr) {
      System.out.print(item+", ");
    }
  }
}

Output

ArrayList: [Java, Python, JavaScript]
Array: Java, Python, JavaScript,

In the above example, we have created an arraylist named languages. Notice the line,

languages.toArray(arr);

Here, the toArray() method converts the arraylist languages into an array. And stores it in the string array arr.

Note: If we don't pass any argument to the toArray() method, the method returns an array of the Object type.


Example 2: Convert Array to ArrayList

import java.util.Arrays;
import java.util.ArrayList;

class Main {
  public static void main(String[] args) {

    // create an array
    String[] array = {"Java", "Python", "C"};
    System.out.println("Array: " + Arrays.toString(array));

    // convert array to arraylist
    ArrayList<String> languages= new ArrayList<>(Arrays.asList(array));

    System.out.println("ArrayList: " + languages);

  }
}

Output

Array: [Java, Python, C]
ArrayList: [Java, Python, C]

In the above example, we have created an array of String type. Notice the expression,

Arrays.asList(array)

Here, the asList() method of the Arrays class converts the specified array into the arraylist.