Java LinkedList Add Array Example

This example shows how to add an array to LinkedList in Java. This example also shows various ways to add an array to LinkedList using asList and addAll methods.

How to add an array to LinkedList in Java?

There are a couple of ways using which you can add an array to the LinkedList object in Java.

1. Using the asList method of the Arrays class

The LinkedList class does not provide any direct method to add all elements of an array. However, we can first convert the array to a List and then add all elements of the List to the linked list.

To convert an array to a List object, we can use the asList method of the Java Arrays class.

The asList method returns a fixed-size list backed by the original array. Once we get a List from the array, we can then add all elements of the list to a linked list using the addAll method of the LinkedList class.

The addAll method adds all the elements of the specified collection to this linked list object.

Output

As you can see from the output, all elements of an array are appended to the end of the linked list object.

2. Using the addAll method of the Collections class

You can also use the addAll method of the Collections class.

The addAll method returns true if the specified collection is changed due to this method call.

Output

What is the preferred way?

The addAll method of the Collections class is the preferred way to add all elements of an array to the linked list object. Since it does not involve an additional step of converting an array to the list, it should perform better than the first approach.

This example is a part of the LinkedList in Java tutorial.

Please let me know your views in the comments section below.

References:
Java 8 LinkedList

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *