Java: Add Items to a Linked List Examples

In this blog post, I’m going to show you the different ways to add items to a Java LinkedList. The Java LinkedList is implemented as a Doubly LinkedList. Here is the class hierarchy of the LinkedList:

Creating a LinkedList and Adding New Items to the End of the LinkedList

The following example shows how to create a LinkedList and add items to the end of the LinkedList. To do this, we use the add method for adding to the end of the LinkedList. The second way of adding to the end of the LinkedList is to use the addLast method.

Output:

Adding New Items to the Front of the LinkedList

The following example shows how to add an item to the front of the LinkedList.  To add to the front off the LinkedList, we use the addFirst method. This example builds ff the code from the last.

Output:

Adding New Items at an Index of the LinkedList

The following example shows how to add an item at the 2nd index of the LinkedList remember LinkedList are zero indexed.  To add at an index, we use the add(index, item) method. This example builds of the code from the last.

Output:

Adding a Collection of Items to a LinkedList

The following example shows how to add a collection of items to a LinkedList. To add a collection of items, we use the addAll method. This example builds off of the code from the last.

Output:

Adding a Collection of Items to a LinkedList at an Index

The following example shows how to add a collection of items to a LinkedList at an index. To add a collection of items, we use the addAll(index, collection) index, items method. This example builds off of the code from the last.

Output:

 

Conclusion

In this blog post, you learn the how to add an item to a LinkedList, how to add an item to the front of a LinkedList, how to add an item at an index in a LinkedList, how to add a collection of items to a LinkedList, and how to add items to a LinkedList at an index.

About the Author Harrison Brock

Harrison Brock is a software engineer that focuses on Full Stack web development

follow me on: