Java List to Array Conversion Tutorial: toArray() Method

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

What is Java List toArray() Method?

The Java List toArray() method is used to copy the elements of a list object and create an array of these elements.

Note: this array how no reference to the target list. That means changing the content of the array won’t affect the other.

Java List toArray() Method Syntax:

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

Object[] toArray()

toArray() Method Parameters:

The toArray() method has two variants.

In the first variant, we put a reference of an array object, we want the elements of the target list to be copied to this array.

In the second variant, the method does not take an argument.

toArray() Method Return Value:

The return value of the first variant is a reference to the array object that we’ve passed as the argument of this method.

For the second variant, the return value is a new array object that contains all the elements of the target list. Note: this returned object is of type Object and we need to cast it to the correct type.

toArray() Method Exceptions:

The method does not throw an exception.

Example: using List toArray() method

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

public class Main {

    public static void main(String[] args){
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);

        Integer iArray[] = new Integer[list.size()];

        iArray = list.toArray(iArray);
        for (int i : iArray){
         System.out.print(", "+i);
        }
    }
}

Output:

, 1, 2, 3, 4, 5, 6, 7

 

Leave a Reply