Convert LinkedList to an array in Java



A LinkedList can be converted into an Array in Java using the method java.util.LinkedList.toArray(). This method has a single parameter i.e. the Array into which the LinkedList elements are to stored and it returns the Array with all the LinkedList elements in the correct order.

A program that demonstrates this is given as follows.

Example

 Live Demo

import java.util.LinkedList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List<String> l = new LinkedList<String>();
      l.add("John");
      l.add("Sara");
      l.add("Susan");
      l.add("Betty");
      l.add("Nathan");
      String[] str = l.toArray(new String[0]);
      System.out.println("The String Array elements are: ");
      for (int i = 0; i < str.length; i++) {
         System.out.println(str[i]);
      }
   }
}

The output of the above program is as follows −

The String Array elements are:
John
Sara
Susan
Betty
Nathan

Now let us understand the above program.

The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. A code snippet which demonstrates this is as follows

List<String> l = new LinkedList<String>();

l.add("John");
l.add("Sara");
l.add("Susan");
l.add("Betty");
l.add("Nathan");

The LinkedList.toArray()method is used to convert the LinkedList into a string array str[]. Then the string array is displayed using a for loop. A code snippet which demonstrates this is as follows


Advertisements