1. Introduction

In Java, a LinkedList can be converted to an array using the toArray method. This method returns an array containing all of the elements in the linked list in proper sequence. In this post, we will learn how to convert a LinkedList to an array in Java.

2. Program Steps

1. Create a LinkedList object and populate it with elements.

2. Use the toArray method to convert the LinkedList to an array.

3. Display the elements of the array to the console.

3. Code Program

import java.util.LinkedList;
import java.util.Arrays;

public class LinkedListToArrayExample {

    public static void main(String[] args) {

        // Step 1: Create a LinkedList object and populate it with elements
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.add("Apple");
        linkedList.add("Banana");
        linkedList.add("Cherry");
        System.out.println("Original LinkedList: " + linkedList);

        // Step 2: Use the toArray method to convert the LinkedList to an array
        String[] array = linkedList.toArray(new String[0]);

        // Step 3: Display the elements of the array to the console
        System.out.println("Array: " + Arrays.toString(array));
    }
}

Output:

Original LinkedList: [Apple, Banana, Cherry]
Array: [Apple, Banana, Cherry]

4. Step By Step Explanation

Step 1: A LinkedList object named linkedList is created and populated with the elements "Apple", "Banana", and "Cherry".

Step 2: The toArray method is invoked on the linkedList object, which converts the linked list to an array of type String. The method takes one argument, which specifies the type of the resulting array; in this case, a new String array is passed as the argument.

Step 3: The elements of the converted array are displayed to the console using the Arrays.toString method. The output shows that the LinkedList has been successfully converted to an array with the elements in the same order.