Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection - Iterator.remove() vs Collection.remove()

As per Sun ,

"Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress."

I have two questions :

  1. What makes this operation "Iterator.remove()" stable than the others ?
  2. Why did they provide a "Collection.remove()" method if it will not be useful in most of the use-cases?
like image 730
AllTooSir Avatar asked Jan 07 '13 16:01

AllTooSir


People also ask

What is difference between remove () method of collection and remove () method of iterator?

As per Sun , "Iterator. remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress."

What is remove method of iterator?

An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown. A program that demonstrates this is given as follows.

Why does iterator remove work?

Removing elements through the iterator works and does not cause exceptions, because this updates the underlying list and the iterator's state that refers to the internals of the list, so everything can stay consistent. However, there is nothing special about iterator. remove() that makes it work in all cases.

What is remove in Java collection?

Method 1: The remove(int index) method of List interface in Java is used to remove an element from the specified index from a List container and returns the element after removing it. It also shifts the elements after the removed element by 1 position to the left in the List. Syntax: remove(int index)


1 Answers

First of all, Collection.remove() is very useful. It is applicable in a lot of use cases, probably more so than Iterator.remove().

However, the latter solves one specific problem: it allows you to modify the collection while iterating over it.

The problem solved by Iterator.remove() is illustrated below:

    List<Integer> l = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4));
    for (int el : l) {
        if (el < 3) {
            l.remove(el);
        }
    }

This code is invalid since l.remove() is called during iteration over l.

The following is the correct way to write it:

    Iterator<Integer> it = l.iterator();
    while (it.hasNext()) {
        int el = it.next();
        if (el < 3) {
            it.remove();
        }
    }
like image 172
NPE Avatar answered Sep 19 '22 14:09

NPE