How to remove the first element of an ArrayList in Java

How to remove the first element of an ArrayList in Java:

This post will show you how to remove the first element of an ArrayList. It is resizable and it is the array implementation of the List interface. The size of an ArrayList grows once we keep adding elements to it.

For removing items, ArrayList provides a method called remove. We can use this method to delete the first element.

Definition of remove:

The remove method is defined as like below:

public E remove(int i)

This method removes the element at index i. The index starts from 0. So, the index of the first element is 0, the index of the second element is 1 etc.

To remove the first element of an ArrayList, we have to pass 0 to this method.

This method returns the element that is removed.

It will throw IndexOutOfBoundsException for invalid index, if the index is negative or if it is greater than or equal to the size of the ArrayList.

Example program:

import java.util.ArrayList;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));

        System.out.println("Given ArrayList: " + arrayList);

        arrayList.remove(0);
        System.out.println("Final ArrayList: " + arrayList);
    }
}

Here,

  • arrayList is the original arraylist.
  • It uses remove to remove the first element. We are passing 0 to this method because we are removing the first element from the arraylist.
  • The last line is printing the final modified arraylist.

If you run this program, it will print output as like below:

Given ArrayList: [1, 2, 3, 4, 5, 6, 7]
Final ArrayList: [2, 3, 4, 5, 6, 7]

As you can see here, the first element is removed. You can also pass any other value as the index to remove any other elements.

Java arraylist remove first element

You might also like: