In this guide, you will learn how to remove a specified element from an ArrayList using remove()
method. The method remove(Object obj)
removes the first occurrence of the specified object(element) from the list. It belongs to the java.util.ArrayList
class.
public boolean remove(Object obj)
Note:
- It returns false if the specified element doesn’t exist in the list.
- If there are duplicate elements present in the list it removes the first occurrence of the specified element from the list.
Java Program to demonstrate ArrayList.remove(Object obj) method
In this example, we have an ArrayList of strings. We can remove a specific string from the list using remove() method.
import java.util.ArrayList;
public class RemoveExample {
public static void main(String args[]) {
//String ArrayList
ArrayList<String> al = new ArrayList<>();
al.add("AA");
al.add("BB");
al.add("CC");
al.add("DD");
al.add("EE");
al.add("FF");
// Displaying arraylist before removing any element
System.out.println("ArrayList before remove:");
for(String var: al){
System.out.println(var);
}
//Removing element AA from the arraylist
al.remove("AA");
//Removing element FF from the arraylist
al.remove("FF");
//Removing element CC from the arraylist
al.remove("CC");
// The element "GG" doesn't exit in the list so this
// method returns false, which is stored in variable b
boolean b = al.remove("GG");
System.out.println("Element GG removed: "+b);
// Displaying arraylist after all the remove operations
System.out.println("ArrayList After remove:");
for(String var2: al){
System.out.println(var2);
}
}
}
Output:
ArrayList before remove: AA BB CC DD EE FF Element GG removed: false ArrayList After remove: BB DD EE
Troy Taylor says
Very clear, very helpful. Thanks ++
Deepika D says
I have a question : if ArrayList list…. is defined and list.remove(Integer) is called.
will it take that Integer parameter as index or as a element of the list ????
Chaitanya Singh says
Lets say we have an arraylist of type integer then using list.remove(1) will remove the element at the position 1. However if you want to remove the element that has value 1 then do it like this: list.remove(Integer.valueOf(1)).