Collections

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. Example also shows how to insert element at specified index in ArrayList.

How to insert element at beginning of ArrayList in Java?

When we add elements to ArrayList using add method, they are inserted at the end of the ArrayList. To insert element at the beginning or start of the ArrayList, use overloaded add method of ArrayList which also accepts 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 element at 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 element at specified index in ArrayList?

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

Output

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

 

Join 1000+ fellow learners! Enter your email address below: