Collections

Java ArrayList remove element example

Java ArrayList remove element example shows how to remove element from ArrayList in Java. Example also shows how to remove all elements or specific element from ArrayList.

How to remove element from ArrayList?

To remove element from ArrayList, use remove method.

This method removes element at specified index from ArrayList. It shifts subsequent elements to the left. remove method returns element which was removed from ArrayList.

Output

You can also use overloaded remove method which accepts the object to be removed instead of index.

This method removes first occurrence of the specified object from the ArrayList. This method returns true if the element was found and removed from the ArrayList, false otherwise.

Output

How to remove objects from ArrayList?

Let’s try to remove objects from ArrayList.

Output

As you can see from the output, object is not removed from the ArrayList. remove method compares the objects to find the object to remove using equals method and Emp class has not implemented equals and hashcode methods. Let’s implement these methods and try again.

Output

How to remove all elements from ArrayList?

You can use clear method of ArrayList to remove all elements from ArrayList.

Output

You can also use removeAll method to remove all elements from ArrayList like given below.

Please let us know your views in the comments section below.

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.