Java program to convert the linkedlist into an array and vice versa

h‮ww//:sptt‬w.theitroad.com

To convert a LinkedList to an array and vice versa in Java, you can use the toArray() method of the LinkedList class and the addAll() method of the List interface.

Here's an example program that demonstrates how to convert a LinkedList to an array and vice versa in Java:

import java.util.LinkedList;
import java.util.List;

public class LinkedListToArrayAndBack {
    public static void main(String[] args) {
        // Create a LinkedList
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.add("apple");
        linkedList.add("banana");
        linkedList.add("cherry");

        // Convert the LinkedList to an array
        String[] array = linkedList.toArray(new String[linkedList.size()]);

        // Print the array
        System.out.println("Array: ");
        for (String s : array) {
            System.out.println(s);
        }

        // Convert the array to a LinkedList
        LinkedList<String> newLinkedList = new LinkedList<>();
        List<String> list = Arrays.asList(array);
        newLinkedList.addAll(list);

        // Print the LinkedList
        System.out.println("LinkedList: ");
        for (String s : newLinkedList) {
            System.out.println(s);
        }
    }
}

In this program, we first create a LinkedList of strings and add some elements to it. We then convert the LinkedList to an array using the toArray() method of the LinkedList class.

Next, we create a new LinkedList and use the addAll() method of the List interface to add the elements of the array to the new LinkedList.

Finally, we print both the array and the LinkedList to the console to verify that the conversion was successful.

When you run the program, the output will be:

Array:
apple
banana
cherry
LinkedList:
apple
banana
cherry

As you can see, the program successfully converts the LinkedList to an array and vice versa, and prints them to the console.