Java LinkedList Add Element at Beginning Example

This example shows how to add an element at the beginning of the LinkedList (front) in Java. The example also shows how to insert an element at any index of the LinkedList.

How to add an element at the beginning of the LinkedList (at the front)?

1. Using the add method

When you add an element to the LinkedList using the add method, by default it is appended at the end of the LinkedList object. What if you want to add an element at the beginning of the LinkedList or at the front of the LinkedList?

Well, in that case, you can use the overloaded add method that also accepts the index argument.

This add method adds the specified element at the specified index in the LinkedList object. It also shifts any element located at the current position and all other subsequent elements to the right by increasing their indices by 1.

In order to add the element at the beginning, we need to call this method with index 0 as given below.

Output

As you can see from the output, the element “Yellow” is inserted at the front i.e. index 0 and all the current subsequent element’s indices are increased by 1 thus shifting them to the right.

2. Using the addFirst method

You can also use the addFirst method declared in the Deque interface to add an element at the front of the LinkedList object.

Output

How to insert an element at the specified index in the LinkedList?

Specify the index at which you want to insert an element in the LinkedList in the add method. All the existing elements will be shifted to the right by the add method automatically.

The below given example inserts the “Black” element at index 1 of the LinkedList object.

Output

As you can see from the output, the “Black” element is inserted at index 1 and the index of the “Green” and “Blue” elements have been increased to 2 and 3 respectively.

This example is a part of the Java LinkedList tutorial with examples.

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

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 *