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 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 the different purpose. The best way to master Collection framework is to pick up a good book and follow it from start to end like Java Generics and Collection, which provides a 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.

Bottom line is that a good knowledge of the Java Collection framework is essential for any Java programmer. In fact, these classes are 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 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 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 expect the caller to provide an array of specified type, but it's also smart enough to make some adjustments into length.

3) If 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 given array is bigger than the linked list than spare buckets are set to null. You can use them to determine 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, 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

Btw, you would need a Pluralsight membership to access this course, which costs around $29 monthly or $299 annually. I have one and I also suggest all developers have that plan because Pluralsight is like NetFlix for Software developers.

It has more than 5000+ good quality courses on all latest topics. Since we programmers have to learn new things every day, an investment of $299 USD is not bad.

Btw, it also offers a 10-day free trial without any obligation which allows you to watch 200 hours of content. You can watch this course for free by signing for that trial.



Java Program to convert LinkedList to an array

Here is a sample Java program which shows you can convert a LinkedList to an array in Java. This program contains two examples, first one converts a LinkedList of String to an array and the second one converts 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 object 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 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.

Further Learning
The Complete Java MasterClass
Java Fundamentals: Collections
Data Structures and Algorithms: Deep Dive Using Java


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 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.

No comments:

Post a Comment