Skip to content

Java ArrayList insert element at beginning example

Java ArrayList insert element at beginning example shows how to insert element at beginning of ArrayList in Java. The example also shows how to insert element at specified index in ArrayList.

How to insert an element at beginning of the ArrayList in Java?

When we add elements to the ArrayList using the add method, they are inserted at the end of the ArrayList. To insert element at the beginning or start of the ArrayList, use the overloaded add method of ArrayList which also accepts an index parameter where the element needs to be inserted.

This method inserts the element at the specified index in the ArrayList. If there is any element exists at the specified position, it shifts the existing elements along with any subsequent elements to the right (means increases their index by 1).

Java ArrayList insert an element at the beginning example

Output

As you can see from the output, we specified index as 0 in the add method to insert element at the start of the ArrayList. List automatically shifted all the existing elements by increasing their index by 1.

How to insert an element at specified index in ArrayList?

Use the add method with the index you want to insert an element in the ArrayList. All subsequent elements (if any) will be shifted right automatically by ArrayList.

Output

You might want to check if the element already exists in the ArrayList before adding it. Check out this example if you want to replace elements in ArrayList.

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

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

About the author

3 comments

  1. Except it does not actually add a new element to the array, nor does it shift the other elements up by one. All it does is modifies the value of the specified element.

    1. Hello Bryan,

      Thanks for the comment. However, I think you might have confused the ArrayList set method with the add method. The ArrayList add method actually adds a new element and shifts other elements, if required, as shown in the example. Your comment fits the description of the set method which replaces the element at specified index.

      I hope it helps.

Leave a Reply

Your email address will not be published.