Java LinkedList toArray() Method Example

The toArray() method of java.util.LinkedList class returns an array containing all of the elements in this list in proper sequence (from first to last element).This method acts as bridge between array-based and collection-based APIs.

Signature

public Object[] toArray()

This method returns a array of Object which contains all the elements of the list.

Example

The following example shows the usage of java.util.LinkedList.toArray() method.

import java.util.LinkedList;

public class ToArrayLinkedListExample {
	public static void main(String args[])
	{
		// create an empty LinkedList
		LinkedList l = new LinkedList();
		
		// use add() method to add elements to the list
		l.add("Element1");
		l.add("Element2");
		l.add("Element3");
		l.add("Element4");
		l.add("Element5");
		
		//Printing the elements of the list
		System.out.println("**Elements of the list **");
		for(String temp:l)
		{
			System.out.println(temp);
		}
		
		// create an array and copy the list to it
	    Object[] array = l.toArray();

	     // Printing elements of the array
	    System.out.println("**Elements of the array**");
	    for(Object val : array)
	    {
	    	System.out.println(val.toString());
	    }
	}
}

Output

**Elements of the list **
Element1
Element2
Element3
Element4
Element5
**Elements of the array**
Element1
Element2
Element3
Element4
Element5

Leave a Reply

Your email address will not be published. Required fields are marked *