Collections

Arraylist remove() Object Java Code With Examples

Table of Contents

Program

import java.util.ArrayList;
public class ArrayObjectRemove
{	

	public static void main(String[] args)
    {
		ArrayList<String> animals=new ArrayList<String>();
        		animals.add("dog");
                animals.add("cat");
                animals.add("cow");
                animals.add("lion");
                animals.add("tiger");
                animals.add("pig");
                System.out.println("Arraylist before removing object:");
         for(String var1:animals)
         {
             System.out.println(var1);
         } 
             	animals.remove("pig");
             	boolean b=animals.remove("cat");
                System.out.println("cat is removed :"+ b);
                System.out.println("Arraylist after removing object");
        for(String var2:animals)
        {
               	System.out.println(var2);
        }
     }
}

Output

   Arraylist before removing object:
   dog
   cat
   cow
   lion
   tiger
   pig
   
   cat is removed:true
   Arraylist after removing object:
   dog
   cow
   lion
   tiger

Description

boolean remove(Object o)

Removes a single instance of the specified element from this collection, if it is present (optional operation). More formally, removes an element e such that (o==null ? e==null : o.equals(e)), if this collection contains one or more such elements. Returns true if this collection contained the specified element (or equivalently, if this collection changed as a result of the call).

Parameters:

o – element to be removed from this collection, if present

Returns:

true if an element was removed as a result of this call

Throws:

ClassCastException – if the type of the specified element is incompatible with this collection (optional)
NullPointerException – if the specified element is null and this collection does not permit null elements (optional)
UnsupportedOperationException – if the remove operation is not supported by this collection