To convert an array into a java.util.LinkedList we can use the java.util.Arrays class’s asList() method. The Arrays class in the java.util package provides a utility method to convert an array to a List. The Arrays.asList() method will convert an array to a fixed size List. To create a LinkedList, we just need to pass the List to the constructor of the java.util.LinkedList class. A java.util.ArrayList could be created in this way too.
The Code
The following code example demonstrates converting an Array of Strings to a LinkedList of Strings.
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26  | 
						import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; /** * Java 1.4+ Compatible * The following example code demonstrates converting an Array of Strings to a LinkedList of Strings */ public class Array2LinkedList {     public static void main(String[] args) {         // initialize array with some data         String[] sa = new String[] { "A", "B", "C" };         // convert array to LinkedList         LinkedList ll = new LinkedList(Arrays.asList(sa));         // iterate over each element in LinkedList and show what is in the list.         Iterator iterator = ll.iterator();         while (iterator.hasNext()) {             // Print element to console             System.out.println((String) iterator.next());         }     } }  | 
					
Result
Here is the output of the above example code showing how to convert an Array of Strings to a LinkedList of Strings.
| 
					 1 2 3  | 
						A B C  | 
					
        				














Leave a Comment