Java LinkedList toArray() Method Tutorial

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

What is Java LinkedList toArray() Method?

The Java LinkedList toArray() method is used to get an array representation of the elements in the target LinkedList object.

Note: this method returns a copy of the elements in the target LinkedList object. This means the two objects will have their own copy of the elements and if one object changes an element, the other won’t take effect.

Java toArray() Method Syntax:

public Object[] toArray()

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

toArray() Method Parameters:

The method has two variants, as you can see in the method’s syntax.

For the second variant, the method takes one argument and that is a reference to an array object that we want to pass the elements in the target LinkedList object there.

toArray() Method Return Value:

The return value of this method:

For the first variant: is a reference to a new array object that contains the entire elements of the target LinkedList.

For the second variant: the return value is a reference to the argument that we’ve passed to the method.

Note:

  • If the size of the target array (the one that we pass as the argument of the method) is larger than the size of the target LinkedList object, then the rest of indexes of the array will be filled with the value null.

toArray() Method Exceptions:

ArrayStoreException: We get this exception if the reference array (the argument) is of incompatible type compared to the elements in the target LinkedList object.

NullPointerException: if the value we set as the argument of the method is null, this exception will be thrown.

Example: using LinkedList toArray() method

import java.util.LinkedList; 
class Main{
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        list.add("John");
        list.add("Omid");
        list.add("Jack");
        list.add("Ellen");
        list.add("Elon");

        String array[] = new String[list.size()];

        list.toArray(array);

        for (String s: array){
            System.out.println(s);
        }
    }
}

Output:

John

Omid

Jack

Ellen

Elon
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies