ArrayList remove(Object o) method in java

Let’s learn ArrayList remove(Object o) method in java.

ArrayList remove(Object o) method in java

remove(Object o) method of ArrayList class removes the first occurrence of the specified element from this list, if it is present.

Also read – ArrayList in java

If the list does not contain the element, it is unchanged.

Syntax:

remove(Object o)

Parameters:

o element to be removed from this list, if present.

Returns:

true if this list contained the specified element.

Now let’s see example on ArrayList remove(Object o) method.

import java.util.ArrayList;
public class ArrayListRemoveObjectExample
{
   public static void main(String[] args)
   {
      // create an empty ArrayList
      ArrayList<String> names = new ArrayList<String>(7);
      names.add("Bharat");
      names.add("Chetan");
      names.add("Dinesh");
      names.add("Bharat");
      names.add("Falguna");
      names.add("Dinesh");
      names.add("Bharat");
      System.out.println("ArrayList before using remove(Object o) method: ");
      for(int a = 0; a < 7; a++)
      {
         System.out.println(names.get(a).toString());
      }
      // removing first occurrence of "Bharat" and "Dinesh"
      names.remove("Bharat");
      names.remove("Dinesh");
      System.out.println("ArrayList after using remove(Object o) method: ");
      for(int a = 0; a < 5; a++)
      {
         System.out.println(names.get(a).toString());
      }
   }
}


Output:

ArrayList before using remove(Object o) method:
Bharat
Chetan
Dinesh
Bharat
Falguna
Dinesh
Bharat
ArrayList after using remove(Object o) method:
Chetan
Bharat
Falguna
Dinesh
Bharat