Write a Java Program to Convert the LinkedList into an Array and vice versa

Java is an object-oriented programming language that supports a variety of data structures, including linked lists and arrays.

Linked lists are dynamic data structures that allow for efficient element insertion and deletion, while arrays are static data structures that offer fast random access to elements.

In some situations, it may be necessary to convert a linked list into an array or vice versa, depending on the requirements of a particular program.

In this tutorial, we will discuss how to convert a linked list into an array and vice versa using Java programming language.


Converting a LinkedList to an Array

To convert a LinkedList to an array, we can use the toArray() method of the LinkedList class.

The toArray() method converts the elements of a LinkedList into an array of type Object.

We can then cast this array into an array of the desired type.

Here’s an example Java program that demonstrates how to convert a LinkedList to an array:

import java.util.LinkedList;

public class LinkedListToArrayExample {
   public static void main(String[] args) {
      LinkedList<String> linkedList = new LinkedList<String>();
      linkedList.add("Apple");
      linkedList.add("Banana");
      linkedList.add("Cherry");
      linkedList.add("Durian");

      String[] array = linkedList.toArray(new String[linkedList.size()]);

      for (String fruit : array) {
         System.out.println(fruit);
      }
   }
}

In this example, we create a LinkedList of Strings and add four elements to it.

We then use the toArray() method to convert the LinkedList to an array of Strings.

Finally, we print each element of the array using a for-each loop.

Converting an Array to a LinkedList

To convert an array to a LinkedList, we can create a new LinkedList and add each element of the array to it using the add() method of the LinkedList class.

Here’s an example Java program that demonstrates how to convert an array to a LinkedList:

import java.util.LinkedList;

public class ArrayToLinkedListExample {
   public static void main(String[] args) {
      String[] array = {"Apple", "Banana", "Cherry", "Durian"};

      LinkedList<String> linkedList = new LinkedList<String>();
      for (String fruit : array) {
         linkedList.add(fruit);
      }

      for (String fruit : linkedList) {
         System.out.println(fruit);
      }
   }
}

In this example, we create an array of Strings and then create a new LinkedList.

We then use a for-each loop to add each element of the array to the LinkedList.

Finally, we print each element of the LinkedList using a for-each loop.


Conclusion

In conclusion, converting a LinkedList to an array or an array to a LinkedList is a straightforward process in Java.

By using the toArray() method or the add() method, we can easily convert between these two data structures, depending on the needs of our program.