How to remove last element from arraylist in java

Let’s learn how to remove last element from arraylist in java.

How to remove last element from arraylist in java

To remove last element from arraylist use two overloaded remove() method of ArrayList. They are,

  • remove(int index): accepts the index of the element to be removed. Pass index of last element to delete last element.
  • remove(Object o): takes input as object to be removed. If there is no duplicates in ArrayList then pass last element value to remove method.

Here’s an example on remove(int index) to last element from arraylist.

import java.util.ArrayList;
import java.util.List;
public class ArrayListRemoveLastElement
{
   public static void main(String[] args)
   {
      List<Integer> al = new ArrayList<>();
      al.add(56);
      al.add(28);
      al.add(39);
      al.add(59);
      al.add(82);
      // using size() method to find index of last element
      int index = al.size() - 1;
      // deleting last element by passing index
      al.remove(index);
      System.out.println("After remove last element from arraylist: " + al);
   }
}


Output:

After remove last element from arraylist: [56, 28, 39, 59]


Here’s an example on how to remove last object from arraylist in java.

import java.util.ArrayList;
import java.util.List;
public class ArrayListRemoveLastElement
{
   public static void main(String[] args)
   {
      List<Integer> al = new ArrayList<>();
      al.add(56);
      al.add(28);
      al.add(39);
      al.add(59);
      al.add(82);
      al.remove(new Integer(82));
      System.out.println("After remove last element from arraylist: " + al);
   }
}


Output:

After remove last element from arraylist: [56, 28, 39, 59]


Also read – operators in java