Copy LinkedList into array - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Friday, December 2, 2016

Copy LinkedList into array

LinkedList is doubly-linked list implementation of the List and Deque interfaces.

How to copy content of Java LinkedList into Array?

Here we will see an example for copying the content of the Java LinkedList into Array. This can be done by calling toArray method on this list.

package com.walking.techie;

import java.util.LinkedList;

public class LinkedListToArrayDemo {

 public static void main(String[] args) {
  LinkedList<String> numbers = new LinkedList<String>();
  numbers.add("First");
  numbers.add("Second");
  numbers.add("Third");
  numbers.add("Fourth");
  System.out.println("Original LinkedList " + numbers);

  String[] stringArr = new String[numbers.size()];
  numbers.toArray(stringArr);
  // print String Array
  System.out.print("Content of Array String created from LinkedList [ ");
  for (String string : stringArr) {
   System.out.print(string + " ");
  }
  System.out.println("]");
 }
}

Output of above program is shown below:

Original LinkedList [First, Second, Third, Fourth]
Content of Array String created from LinkedList [ First Second Third Fourth ]

No comments :

Post a Comment