Java Utility Library

Java ArrayList - toArray() Method



The java.util.ArrayList.toArray() method returns an array containing all of the elements in the list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the given list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of the given list.

If the list fits in the specified array with room to spare, the element in the array immediately following the end of the list is set to null.

Syntax

public <T> T[] toArray(T[] a)

Parameters

a Specify the array into which the elements of the ArrayList are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Return Value

Returns an array containing all elements of the list.

Exception

  • Throws ArrayStoreException, if the runtime type of a is not a supertype of the runtime type of every element in the list.
  • Throws NullPointerException, if the given array is null.

Example:

In the example below, the java.util.ArrayList.toArray() method returns an array containing all elements of the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an ArrayList
    ArrayList<Integer> MyList = new ArrayList<Integer>();

    //populating ArrayList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(40);

    //creating an empty array
    Integer[] Arr = new Integer[5];

    //convert the list into an array
    MyList.toArray(Arr);

    //print the array
    System.out.print("The Arr contains: ");
    for(int i = 0; i < Arr.length; i++)
      System.out.print(Arr[i]+ " ");
  }
}

The output of the above code will be:

The Arr contains: 10 20 30 40 null

❮ Java.util - ArrayList