How to remove an element from ArrayList in Java

By | August 9, 2020

How to remove an element from ArrayList in Java:

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

We can remove an element from ArrayList in java using below methods.

1 Using remove() methods.

2. Using iterator.remove() method

 

1. remove() methods:

ArraysList has provided two overloaded methods of remove.

a. remove(int index):

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.
Parameters:

index – the index of the element to be removed

Returns:

the element previously at the specified position

Example:

Output:

b. remove(Object 0):

If you want to remove an element based on it value then you can use this method.

Removes the first occurrence of the specified element from this list, if it is present. If this list does not contain the element, it is unchanged. It removes the element with the lowest index i. Returns true if this list contained the specified element.

Example:

Output:

 

2. Using iterator.remove() method:

If you have hundreds of elements in an ArrayList, it is difficult to remove the element based on its index. Using iterator we can loop through the elements and can remove the elements.

Output:

Value “three” is present two times in the list. Using iterator we are able to remove all the occurrences of “three”.

 

Recommended Posts:

How to remove last element from an ArrayList in Java

How to generate random number in Java

StringUtils examples

Convert String to String array

Star pattern programs in Java

TestNG

Mouse-hover actions in Selenium WebDriver

 

Tags: remove an element from arraylist in java, how to remove an element from arraylist in java

 

arrays tostring in java | selenium interview questions | binary search

 

 

 

 

 

Play & Win contest by Selenium99

Home 1

Leave a Reply

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