Open In App

Java Program to Remove a Specific Element From a Collection

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

remove() method is used to remove elements from a collection. It removes the element at the specified position in this list. Shifts any subsequent elements to the left by subtracts one from their indices. In simpler words, the remove() method is used for removing the element from a specific index from a list by removing the value and returning the same.

Approaches: There are two standard methods defined over this method which are as follows.

  1. remove(int index)
  2. remove(Object obj)

Method 1: The remove(int index) method of List interface in Java is used to remove an element from the specified index from a List container and returns the element after removing it. It also shifts the elements after the removed element by 1 position to the left in the List. 

Syntax:

remove(int index)

Parameters: It takes one parameter of int type as traversing over-index where the index value is the value to be removed from the list. 

Return Type: An ArrayList of which some elements have been deleted.

Exceptions: As dealing with indices with the size specified so definitely ArrayOutOfBounds is thrown in two scenarios

  • Either index mention is negative
  • Index mentioned is beyond(greater) the index of the ArrayList

Example:

 
 


Output
Original ArrayList : [10, 20, 30, 1, 2]
Modified ArrayList : [10, 1, 2]

Method 2: The remove(Object obj) method of List interface in Java is used to remove the first occurrence of the specified element obj from this List if it is present in the List.

Syntax:

boolean remove(Object obj)


Parameters: It accepts a single parameter obj of List type which represents the element to be removed from the given list.

Return Value: It returns a boolean value True after removing the first occurrence of the specified element from the List and otherwise if the element is not present in the List then this method will return False.

Example:

Output:

Modified ArrayList : [10, 20, 30]


Note: Sometimes it does throw a warning of using deprecated function call or object. One can recompile like to figure out where it is occurring. Generally, it is a bad idea to use deprecated libraries that may go away in the next release.


 


Similar Reads