remove() in Java

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

The remove method is often used in the Java Collection framework. The remove method removes the specified element from any collection of objects. However, the ways to remove an object might differ in one case or the other.

Syntax

The remove() method in ArrayList allows you to remove an element in two different ways.

  • To begin with, you are supposed to know the object itself to get it removed from the list.

    The specified object will be removed from the list, and the subsequent objects will be shifted by one place to the left.

    ArrayList allows the insertion of duplicate objects. So if the same object is present at multiple positions, the above remove method will remove its first occurrence only.

  • The other way is to indicate the index of the element as a parameter.

    The above method removes the element present at the specified index and shifts the subsequent elements by one place to the left.

Parameters of remove() in Java

The remove method takes a single parameter.

  • obj: The object in the ArrayList is to be removed.

Alternatively,

  • index: The element at the mentioned position will be removed.

Return values of remove() in Java

  • The remove method returns true if an object passed as a parameter is removed from the list. Otherwise, it returns false.
  • The remove method returns the removed element if an index is passed.
    • It throws IndexOutOfBoundsException if the specified index is not in range.
  • The time complexity of both methods will be O(N).

Example

The given figure also shows the use of boxing an argument so that the remove() method considers the actual object instead of the ASCII value of any char data. Return values of remove() in Java

The return value depends on the parameter of the remove method.

Since character A is present inside the list, the remove method will remove the character and return true.

But what if we pass a character not present in the ArrayList? The remove method simply returns false in this case.

Time Complexity of remove(int index) Method

The time complexity of the remove(int index) Method is O(N).

Reason:

ArrayList implements a RandomAccess interface, so accessing any random element will be done in O(1) complexity. However, since the remaining elements must be shifted by one place to their left, the overall time complexity becomes O(N).

Alternatively, if the index is passed as a parameter, the remove method will remove and return the removed element as well. However, if the index is not in the range of the ArrayList, the remove method throws IndexOutOfBoundsException.

IndexOutOfBoundsException.

Time complexity of remove(Object obj) Method

The time complexity of the remove(Object obj) method is O(N).

Reason:

When we pass an object to the remove method, it has to iterate through every element in the list until it finds the one needed for removal. And obviously, the remaining elements on the right also need to be shifted. So, the overall time complexity is O(N).

Exceptions for remove() in in Java

IndexOutOfBoundsException

The java.lang.IndexOutOfBoundsException exception is thrown when the index in the remove(int index) method is out of range.

ConcurrentModificationException

When we use this method while iterating over the elements of the ArrayList, it may result in ConcurrentModificationException because such modifications are not allowed in the ArrayList while iterating over its elements simultaneously.

Solution to ConcurrentModificationException: Iterator interface

The alternative here is to use the remove method of the Iterator interface.

Syntax:

Implementation:

Output

Example

Let us consider a simple example of an ArrayList that stores several characters. We need to focus on what happens when we remove an element from the ArrayList.

Output:

Time Complexity:

Notice that the removal of C also led to shifting all its proceeding elements by one place to their left.

We'll look at a few more examples to understand the variants of the remove method.

remove() in Java

The remove method in Java has varied uses in the Collection interface. Although the operation simply removes an object from a collection of objects, it has several variants, each with different parameters and return values.

In our discussion, we'll primarily focus on using the remove method in ArrayList. Also, the use of the remove method in Set, Maps and Queues has been demonstrated in the end.

More Examples

1. Remove the Specified Element From the ArrayList

Output:

Time Complexity:

2. Remove the Element from the Specified Position

Output:

Time Complexity:

3. Remove the First Occurrence of the Element

If an element appears more than once in the ArrayList, it will only remove it at the first location.

Output:

Other Uses of Remove() in Java

The remove() method is also implemented in the other interfaces, including Set, Queue, Maps, etc. Let us take a quick look at some of the examples related to each of these interfaces where the remove() method is used. Since Set, Queue, and Maps are interfaces, we'll need a class that implements these interfaces to create objects.

Queue

Queue is a data structure that follows the First In First Out (FIFO) order. It is similar to a real queue where the person at the front end of the queue will be favoured first. The Queue interface is already present in Java and has been implemented by other classes. The class LinkedList has been used to implement the Queue interface.

Output:

Time Complexity: O(N) where N is the size of the Linked List.

Explanation:

  • LinkedList class in Queue has an array as its underlying data structure. So, the removal of any element doesn't require the shifting of other elements.
  • However, we still have to traverse the LinkedList to find the element to be removed.

Set

Set is a Collection interface in Java that contains a group of objects without maintaining their insertion order. Also, it doesn’t allow the insertion of duplicate values.

For the Set interface, we’ll be demonstrating with the help of LinkedHashSet.

Output:

Time Complexity: O(1)

Reason:

  • LinkedHashSet is the combination of HashSet as well as LinkedList. The remove method in LinkedHashSet works in O(1) time complexity.
  • It is because LinkedHashSet maintains links between the nodes in addition to the hash table.
  • It is unnecessary to traverse the whole list for removal; only the list of neighbours needs to be updated.
  • Accessing a specific element is no more expensive than accessing the HashSet.

Map

Map is an interface that stores a group of key-value pairs as objects, where a key can be used to fetch its mapped value. We'll use HashMap to implement the Map interface.

Output:

Time Complexity: O(1)

Reason:

** HashMap ** uses ** Hash Table ** as its data structure. The remove method in HashMap consumes O(1) time. The put method also has O(1) time complexity. So, the overall time complexity will be O(1).

Conclusion

  • The remove method is present in the Java Collection framework. We can remove an element from a collection of objects with the help of remove() in java.
  • There are two ways to pass a parameter to the remove method.
  • If we pass an object, then the remove method returns true if the removal is successful; otherwise, it returns false. boolean remove (Object obj);
  • If an index is passed as a parameter, the remove method removes the element at the specified index. Object remove(int index); If the index is out of range of the ArrayList, it will throw IndexOutOf BoundsException. If the same element occurs multiple times in the ArrayList, the remove method will remove only the first occurrence. The overall time complexity of both variations of the remove method in ArrayList will be O(N), where N is the number of inputs.
  • Using ArrayList.remove() method while iteration may result in ConcurrentModificationException.
  • The remove method also finds its use in the interfaces like Set, Map, Queue, etc.