Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Java ArrayList remove(Object obj) Method example

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



This post first appeared on Java Hungry, please read the originial post: here

Share the post

Java ArrayList remove(Object obj) Method example

×

Subscribe to Java Hungry

Get updates delivered right to your inbox!

Thank you for your subscription

×