How to convert LinkedList to Array in Java?

Given a Linked List in Java, the task is to convert this LinkedList to Array.

Examples:

Input: LinkedList: ['G', 'e', 'e', 'k', 's'] 
Output: Array: ['G', 'e', 'e', 'k', 's'] 

Input: LinkedList: [1, 2, 3, 4, 5]
Output: Array: [1, 2, 3, 4, 5] 


Approach:

  1. Get the LinkedList
  2. Convert the LinkedList to Object array using toArray() method.
  3. Convert the Object array to desired type array using Arrays.copyOf() method.
  4. Return the print the Array

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to convert
// LinkedList to Array
  
import java.util.*;
  
public class GFG {
  
    // Function to convert LinkedList to Array
    public static <T> Object[] convertLinkedListToArray(LinkedList<T> linkedList)
    {
  
        // Converting LinkedList to Array
        Object[] array = linkedList.toArray();
  
        return array;
    }
  
    public static void main(String args[])
    {
        // Creating linked list
        LinkedList<String>
            linkedList = new LinkedList<String>();
  
        // Adding elements to the linked list
        linkedList.add("G");
        linkedList.add("e");
        linkedList.add("e");
        linkedList.add("k");
        linkedList.add("s");
  
        // Print the LinkedList
        System.out.println("Linked list: "
                           + linkedList);
  
        // Converting LinkedList to Object Array
        Object[] objArray = convertLinkedListToArray(linkedList);
  
        // Convert Object[] to String[]
        String[] array = Arrays.copyOf(objArray,
                                       objArray.length,
                                       String[].class);
        // Print the String Array
        System.out.println("Array: "
                           + Arrays.toString(array));
    }
}

chevron_right


Output:

Linked list: [G, e, e, k, s]
Array: [G, e, e, k, s]


My Personal Notes arrow_drop_up

Technical Content Engineer at GeeksForGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.