Syntax error Create an object array from elements of LinkedList in Java

Create an object array from elements of LinkedList in Java



An object array can be created from the elements of a LinkedList using the method java.util.LinkedList.toArray(). This method returns the object 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;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Amy");
      l.add("Sara");
      l.add("Joe");
      l.add("Betty");
      l.add("Nathan");
      Object[] objArr = l.toArray();
      System.out.println("The object array elements are: ");
      for (Object i: objArr) {
         System.out.println(i);
      }
   }
}

Output

The output of the above program is as follows −

The object array elements are:
Amy
Sara
Joe
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

LinkedList<String> l = new LinkedList<String>();
   
l.add("Amy");
l.add("Sara");
l.add("Joe");
l.add("Betty");
l.add("Nathan");

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

Object[] objArr = l.toArray();
   
System.out.println("The object array elements are: ");

for (Object i: objArr) {
   System.out.println(i);
}
Updated on: 2020-06-29T13:45:11+05:30

446 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements