Java Program to Remove a Specific Element From a Collection
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.
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.
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
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.
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.
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.
Please Login to comment...