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 :
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."
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.
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.
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)
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With