Open In App

LinkedList toArray() Method in Java

Last Updated : 10 Mar, 2025
Comments
Improve
Suggest changes
3 Likes
Like
Report

In Java, the toArray() method is used to convert a LinkedList into an Array. It returns the same LinkedList elements but in the form of an Array only.

Example: Here, we use toArray() to convert a LinkedList into an Array of Integer.


Output
The LinkedList: [10, 20, 30, 40, 50]
After converting LinkedList to Array: 10 20 30 40 50 

Now there are two method to convert LinkedList into an Array i.e. one with toArray() without parameter and one with toArray(arrayName) with parameter.

1. toArray() - Without Parameter

In Java, the toArray() method without parameter returns an array containing all the elements in the list in proper sequence . The returned array will be safe as a new array is created (hence new memory is allocated). Thus the caller is free to modify the array. It acts as a bridge between array-based and collection-based APIs. 

Syntax:

Object[] toArray();

  • Parameters: It does not take any parameter. 
  • Return Type: It returns an array of object containing all the elements in the list. 

Example: Here, we use toArray() without parameter to convert a LinkedList into an Array of Integer.


Output
The LinkedList is: [1, 2, 3, 4]
After converted LinkedList to Array: 1 2 3 4 


2. toArray(arrayName) - With Parameter

In Java, the toArray() method with parameter also returns an array containing all the elements in the list in proper sequence.

  • If the array is larger than the LinkedList, the toArray() method fills the array with the elements from the LinkedList, and the remaining positions are filled with null.
  • If the array is smaller than the LinkedList, the toArray() method creates a new array of the correct size and fills the array with the elements from the LinkedList.

Syntax:

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

  • Parameters: It takes an array as a parameter. which should be of the same type as the element of the LinkedList.
  • Return Type: It return an array containing elements similar to the LinkedList. 

Exceptions: The method might throw two types of exceptions

  • ArrayStoreException: When the mentioned array is of a different type and is not able to compare with the elements mentioned in the LinkedList.
  • NullPointerException: If the array is Null, then this exception is thrown.

Example: Here, we use toArray(arrayName) with parameter to convert a LinkedList into an Array of String.


Output
The LinkedList: [Welcome, To, Geeks, For, Geeks]
After converted LinkedList to Array: Welcome To Geeks For Geeks 

Next Article
Article Tags :
Practice Tags :

Similar Reads