In C#, the IEnumerator interface defines a way to traverse a collection and look at the elements. I think this is tremendously useful because if you pass IEnumerable<T>
to a method, it's not going to modify the original source.
However, in Java, Iterator defines the remove operation to (optionally!) allow deleting elements. There's no advantage in passing Iterable<T>
to a method because that method can still modify the original collection.
remove
's optionalness is an example of the refused bequest smell, but ignoring that (already discussed here) I'd be interested in the design decisions that prompted a remove
event to be implemented on the interface.
What are the design decisions that led to remove
being added to Iterator
?
To put another way, what is the C# design decision that explicitly doesn't have remove
defined on IEnumerator
?
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.
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."
Iterator in Java is used to traverse each and every element in the collection. Using it, traverse, obtain each element or you can even remove. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements. The iterator() method is provided by every Collection class.
Approach 1: Using Iterator The Iterator object is used to iterate over the elements of the list using the hasNext() and next() methods. An if the condition is used within the while loop and when the condition is satisfied, the particular element is removed using the remove() method.
Iterator
is able to remove elements during iteration. You cannot iterate collection using iterator and remove elements from target collection using remove()
method of that collection. You will get ConcurrentModificationException
on next call of Iterator.next()
because iterator cannot know how exactly the collection was changed and cannot know how to continue to iterate.
When you are using remove()
of iterator it knows how the collection was changed. Moreover actually you cannot remove any element of collection but only the current one. This simplifies continuation of iterating.
Concerning to advantages of passing iterator or Iterable: you can always use Collection.unmodifireableSet()
or Collection.unmodifireableList()
to prevent modification of your collection.
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