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).

Syntax

public Object[] toArray()

Parameters

No parameter is required.

Return Value

Returns an array containing all elements of the list.

Exception

NA

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); 

    //convert the list into an array
    Object[] Arr =  MyList.toArray();

    //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

❮ Java.util - LinkedList