How to remove last element from an ArrayList in Java

By | August 23, 2020

How to remove last element from an ArrayList in Java:

The ArrayList class is a resizable array and it can be found in the java.util package.

We can remove the last element from an ArrayList using remove() method.

1 remove(int i)

2 remove(Object obj)


1. remove(int i) method:

First get the size of the array and then we can use this size to remove the last element.

Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.



2. remove(Object obj) method:

If all the elements in the ArrayList are unique then we can directly pass the element value directly as an Object. It removes the first occurrence of the specified element from this list. So make sure that list is unique before choosing this method to remove the element.




Recommended Posts:

How to clear an ArrayList in Java

How to remove an element from ArrayList in Java

Binary Search in Java

How to generate random number in Java



Tags: remove last element from an ArrayList in Java

Leave a Reply

Your email address will not be published. Required fields are marked *