Java ArrayList toArray() Tutorial

In this section, we will learn what the ArrayList toArray() method is and how to use it in Java.

What is Java ArrayList toArray () Method?

The Java ArrayList toArray() method is used to convert an ArrayList object to an array.

Java ArrayList toArray () Method Syntax:

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

toArray () Method Parameters:

The method takes one argument and that is a reference to the target array we want to copy the content of the ArrayList object into.

toArray () Method Return Value:

The return value of this method is a reference to the array that we’ve copied the content of the ArrayList object into.

toArray () Method Exceptions:

There are two exceptions that this method might throw:

ArrayStoreException: This exception will be thrown if the data type of the target array object (that we set as the argument of this method) is not a super-type of the elements in this list object. For example, if the data type of the target array is integer but we’re having a list of type String!

NullPointerException: If you put a null value as the argument of this method.

Example: using ArrayList toArray () method

import java.util.List; 
import java.util.ArrayList; 

public class Main {

    public static void main(String[] args){
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        Integer iArray[] = new Integer[list.size()]; 
        list.toArray(iArray);
        for (int i :iArray){
         System.out.println(i);
        }
    }
}

Output:

1

2

3

4

5

6
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies