How to Convert a LinkedList to an Array in Java? Example

You can convert a LinkedList to an array in Java by using the toArray() method of the java.util.LinkedList class. The toArray() method accepts an array of relevant type to store contents of LinkedList. It stores the elements in the array in the same order they are currently inside the LinkedList. By using the toArray() method you can convert any type of LinkedList e.g. Integer, String or Float to any type of Array, only catch is this you cannot convert a LinkedList to an array of primitives i.e. a LinkedList of Integer cannot be converted into an array of ints by using toArray() method, but you can convert it to an array of Integer objects, that's perfectly Ok.

Similarly, you can convert a LinkedList of Double to an array of Double and LinkedList of Float objects to an array of Float objects in Java.

Btw, the Java Collection framework is vast as it contains so many classes for different purposes. The best way to master the Collection framework is to pick up a good book and follow it from start to end like Java Generics and Collection, which provides comprehensive coverage of all important classes of Java Collection framework like ArrayList, Vector, HashMap, HashSet, etc.

Alternatively, you can also follow a good core Java course like The Complete Java MasterClass, which also coverers changes made in Java 8  like lambda expression and streams, which has completely changed how you use Collection classes in Java.

The bottom line is that a good knowledge of the Java Collection framework is essential for any Java programmer. In fact, these classes are the bread and butter of Java programming and you will often find them using in your day-to-day programming tasks.




Important points about toArray() methods

Since the toArray() method is used to convert LinkedList to an array in Java, it's important to learn more about it. In fact, you can use this method to convert any type of list to an array in Java as I have previously discussed while we are converting ArrayList to an array in Java.

Let's revise some of the important points about this useful method:

1) This method returns an array containing all of the elements in the given linked list in the same sequence i.e. it keeps the order intact. This is possible because LinkedList implements java.util.List interface which is an ordered collection and guarantees insertion order of elements.

2) The toArray() method expects the caller to provide an array of a specified type, but it's also smart enough to make some adjustments into length.

3) If the given array is not big enough to store all elements of the LinkedList a new array is created of the same runtime type and size of the LinkedList.

4) If the given array is bigger than the linked list then spare buckets are set to null. You can use them to determine the true length of the array if you know that list cannot contain null elements.

If you are interested in learning more about this method or in general, the Java Collection framework, I strongly suggest you join the Java Fundamentals: Collections course on Pluralsight. One of the most comprehensive courses on this topic.

How to Convert LinkedList to Array in Java? Example





Java Program to convert LinkedList to an array

Here is a sample Java program that shows you can convert a LinkedList to an array in Java. This program contains two examples, the first one converts a LinkedList of String to an array and the second one converts the LinkedList of Integer to an array of Integer.

As I have said, you cannot convert LinkedList of wrapper objects to an array of primitive objects e.g. LinkedList of Double cannot be converted to an array of double primitives, for that you need to loop through the list and manually insert each element into an array to take advantage of autoboxing.

Btw, after Java 8, you can also use the map() method to convert a list of Integer objects into an array of Integer objects.

Btw, If you are yet to start Java 8 then I suggest you take a look a these free Java 8 courses to start with. It's very important for a Java developer to get familiar with Java 8 changes.

Anyway, here is our sample program to convert a LinkedList to an array of the same type in Java:

import java.util.Arrays;
import java.util.LinkedList;


public class LinkedListToArray {

public static void main(String args[]){

// creating and initializing a LinkedList of String
LinkedList<String> listOfBooks = new LinkedList<>();
listOfBooks.add("Effective Java");
listOfBooks.add("Clean Code");
listOfBooks.add("Clean Coder");

// printing the contents of LinkedList before conversion
System.out.println("LinkedList: " + listOfBooks);

// Converting the LinkedList to array
String[] arrayOfBooks = listOfBooks.toArray(new String[listOfBooks.size()]);


// printing contents of array after conversion
System.out.println("String array: " + Arrays.toString(arrayOfBooks));


// Second example - Creating LinkedList of Integers
LinkedList<Integer> listOfScores = new LinkedList<>();
listOfScores.add(100);
listOfScores.add(171);
listOfScores.add(264);

// printiing LinkedList
System.out.println("LinkedList: " + listOfScores);

// converting LinkedList of Integer to array of integers
// int[] score = listOfScores.toArray(new int[listOfScores.size()]);
// compile time error
Integer[] scores = listOfScores.toArray(new Integer[listOfScores.size()]); 
// this is ok

// printing array
System.out.println("Integer array: " + Arrays.toString(scores));
}
}

Output:
LinkedList: [Effective Java, Clean Code, Clean Coder]
String array: [Effective Java, Clean Code, Clean Coder]
LinkedList: [100, 171, 264]
Integer array: [100, 171, 264]


That's all about how to convert a LinkedList to the array in Java. Just remember that you can use the toArray() method for this conversion. It also maintains the order of elements and can create a new array if a given array is not big enough to store all elements.

Related LinkedList and Java Collection tutorials, articles
  • How to add an element at first and the last position of LinkedList in Java? (answer)
  • The difference between LinkedHashMap and HashMap in Java? (answer)
  • The difference between ArrayList and LinkedList in Java? (answer)
  • How to find the length of a singly linked list in Java? (solution)
  • How to find the middle element of linked list in Java? (answer)
  • How to find if a linked list contains a loop in Java? (answer)
  • A comprehensive guide to Java Collection (read here)
  • 30 linked list based Coding Questions from Interviews (questions)
  • 100+ Data Structure and Algorithm Questions for Programmers (list)
  • 75+ Coding Questions to crack any programming interviews (questions)
  • 10 Data Structure and Algorithm courses for Interviews (courses)

Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any questions or feedback then please drop a note. 

P. S. - If you don't mind learning from free resources then you can also check this list of free algorithms courses to start with.

2 comments:

  1. Hi There

    I am learning myself some java, so please excuse stupid questions

    How do I add a matrix as an element say k[i]

    Appreciate the effort

    Phil

    ReplyDelete
    Replies
    1. Hello Phil,
      No question is stupid question. If you are talking about array then just doing k[i]= 2 will store 2 at index 2 which would be 3rd element since array starts with zero. You can see my post complete guide to array in Java for more details.

      Delete

Feel free to comment, ask questions if you have any doubt.