Java Utility Library

Java LinkedList - toArray() Method



The java.util.LinkedList.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)

Here, T is the type of element maintained by the container.


Parameters

a Specify the array into which the elements of the LinkedList 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.LinkedList.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 a linkedlist
    LinkedList<Integer> MyList = new LinkedList<Integer>();

    //populating linkedlist 
    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 - LinkedList