In the last tutorial I have shared how to remove Element at the specified index in Arraylist using remove(int index) method. In this tutorial we will use remove(Object obj) method which removes the specified object from the list. Syntax :
public boolean remove(Object obj)
According to Oracle docs, remove(Object obj) removes the first occurrence of the specified element from the list , if it is present. It returns false if the specified element doesn't exist in the list.
remove(Object obj) example
import java.util.*;
public class RemoveMethodExample {
public static void main(String args[]) {
//String ArrayList
ArrayListString> al = new ArrayListString>();
al.add("AA");
al.add("BB");
al.add("CC");
al.add("DD");
al.add("EE");
al.add("FF");
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");
/*This element is not present in the list so
* it should return false
*/
boolean bool=al.remove("GG");
System.out.println("Element GG removed: "+bool);
System.out.println("ArrayList After remove:");
for(String var: al){
System.out.println(var);
}
}
}
Output
ArrayList before remove:
AA
BB
CC
DD
EE
FF
Element GG removed: false
ArrayList After remove:
BB
DD
EE