Java.util.ArrayList.remove(Object o) Method Example

The java.util.ArrayList.remove(Object o) method removes the first occurrence of the element from the list if it is present. If the element is not present then it leaves the list untouched

Signature

public boolean remove(Object o) 

This method removes the first occurrence of the element of the list and returns true if the removal was successful.

Example

The following example shows the usage of java.util.Arraylist.remove(o) method.

import java.util.ArrayList;

public class RemoveMethodArrayListExample 
{
	public static void main(String args[])
	{
		// create an empty array list
		ArrayList al = new ArrayList();
		
		// use add() method to add elements to the list
		al.add("Element1");
		al.add("Element2");
		al.add("Element3");
		
		//removing element at second position 
		boolean flag = al.remove("Element2");
		
		System.out.println("Was the removal successful??? "+flag);
		
		//Printing the elements of the list
		System.out.println("Elements of the list");
		for(String temp:al)
		{
			System.out.println(temp);
		}
	}
}

Output

Was the removal successful??? true
Elements of the list
Element1
Element3

Leave a Reply

Your email address will not be published. Required fields are marked *