The method remove(Object obj)
removes the specified object 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.
Example
In this example we have an ArrayList<String> and we are removing few strings from the list.
package beginnersbook.com; import java.util.ArrayList; public class RemoveExample { public static void main(String args[]) { //String ArrayList ArrayList<String> al = new ArrayList<String>(); 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 b=al.remove("GG"); System.out.println("Element GG removed: "+b); 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)).