In this example, we will learn to convert the linked list into an array and vice versa in Java.
Example 1: Convert the LinkedList into Array
import java.util.LinkedList; class Main { public static void main(String[] args) { LinkedList<String> languages= new LinkedList<>(); // Add elements in the linked list languages.add("Java"); languages.add("Python"); languages.add("JavaScript"); System.out.println("LinkedList: " + languages); // Create a new array of String type String[] arr = new String[languages.size()]; // Convert LinkedList into the string array languages.toArray(arr); System.out.print("Array: "); for(String item:arr) { System.out.print(item+", "); } } }
Output
LinkedList: [Java, Python, JavaScript] Array: Java, Python, JavaScript,
In the above example, we have created a linked list named languages. Notice the line,
languages.toArray(arr);
Here, the toArray()
method converts the linked list languages into an array. And stores it in the string array arr.
Note: If we don’t pass any argument to the toArray()
method, the method returns an array of the Object
type.
Example 2: Convert Array to LinkedList
import java.util.Arrays; import java.util.LinkedList; class Main { public static void main(String[] args) { // create an array String[] array = {"Java", "Python", "C"}; System.out.println("Array: " + Arrays.toString(array)); // convert array to a linked list LinkedList<String> languages= new LinkedList<>(Arrays.asList(array)); System.out.println("LinkedList: " + languages); } }
Output
Array: [Java, Python, C] LinkedList: [Java, Python, C]
In the above example, we have created an array of String
type. Notice the expression,
Arrays.asList(array)
Here, the asList()
method of the Arrays
class converts the specified array into the linked list.