Google News
logo
Java Program to Convert the LinkedList into an Array and vice versa
In the following example of Java program to convert a LinkedList into an array and vice versa :
Program :
import java.util.Arrays;
import java.util.LinkedList;

public class Main {
    public static void main(String[] args) {
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.add("Java");
        linkedList.add("Python");
        linkedList.add("C++");
        linkedList.add("JavaScript");
        linkedList.add("Ruby");
        linkedList.add("PHP");

        // Convert LinkedList to Array
        String[] array = linkedList.toArray(new String[0]);
        System.out.println("Array: " + Arrays.toString(array));

        // Convert Array to LinkedList
        LinkedList<String> linkedListFromArray = new LinkedList<>(Arrays.asList(array));
        System.out.println("LinkedList: " + linkedListFromArray);
    }
}
Output :
Array: [Java, Python, C++, JavaScript, Ruby, PHP]
LinkedList: [Java, Python, C++, JavaScript, Ruby, PHP]
In the above program, we first create a LinkedList object and add some elements to it using the add() method. To convert a LinkedList to an array, we can use the toArray() method and pass a new array of the appropriate type and size as an argument.

In this case, we pass a new String array of size 0, which will be replaced with an array of the appropriate size by the toArray() method. We then print the resulting array to the console using the Arrays.toString() method.

To convert an array to a LinkedList, we first create a new LinkedList object and pass the array to the Arrays.asList() method, which returns a List object that we can pass to the LinkedList constructor. We then print the resulting linked list to the console.