Java ArrayList toArray()

The syntax of the toArray() method is:

arraylist.toArray(T[] arr)

Here, arraylist is an object of the ArrayList class.


toArray() Parameters

The toArray() method can take a single parameter.

  • T[] arr (optional)- an array where elements of the arraylist are stored

Note: Here, T specifies the type of the array.


toArray() Return Values

  • returns an array of T types if the parameter T[] arr is passed to the method
  • returns an array of Object type if the parameter is not passed

Example 1: ArrayList toArray() Method with Parameter

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("C");
    System.out.println("ArrayList: " + languages);

    // Create a new array of String type
    // size of array is same as the ArrayList
    String[] arr = new String[languages.size()];

    // Convert ArrayList into an array
    languages.toArray(arr);

    // print all elements of the array
    System.out.print("Array: ");
    for(String item:arr) {
      System.out.print(item+", ");
    }
  }
}

Output

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

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

languages.toArray(arr);

Here, we have passed an array of String type as an argument. Hence, all elements of the arraylist are stored in the array.

Note: The size of the array passed as an argument should be equal or greater than the arraylist. Thus, we have used the ArrayList size() method to create the array of the same size as the arraylist.


Example 2: ArrayList toArray() Method without Parameter

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("C");
    System.out.println("ArrayList: " + languages);

    // Convert ArrayList into an array
    // the method has no parameter
    Object[] obj = languages.toArray();

    // print all elements of the array
    System.out.print("Array: ");
    for(Object item : obj) {
      System.out.print(item+", ");
    }
  }
}

Output

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

In the above example, we have used the toArray() method to convert the arraylist into an array. Here, the method does not include the optional parameter. Hence, an array of objects is returned.

Note: It is recommended to use the toArray() method with the parameter.