GrantRobertson
GrantRobertson

Reputation: 479

When implementing the Iterable interface, shouldn't the iterator() method return a clone of the collection?

I have seen many examples of how to implement the Iterable interface where the iterator() method merely returns the original collection to be iterated. But this seems to defy part of the purpose of an iterator, in that one should be able to iterate over said collection without worrying about the collection changing underneath you. Shouldn't the iterator() method of an Iterable always return a clone of the collection? And, preferably, a deep clone?

I know, answers to this question may be partially based on opinion, which is verboten. However, what I am trying to get at is the original intent of the Iterable interface, NOT what people may or may not have decided to do with it.

Upvotes: 3

Views: 78

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

But this seems to defy part of the purpose of an iterator, in that one should be able to iterate over said collection without worrying about the collection changing underneath you.

This is not one of the guarantees an iterator gives you. In fact, there is a special exception ConcurrentModificationException created for the purposes of alerting the programmer to the situation when the collection he is iterating has been modified underneath him.

Shouldn't the iterator() method of an Iterable always return a clone of the collection? And, preferably, a deep clone?

It definitely could. However, this would be massively expensive, especially for an operation so fundamental. Think about it: every time you wish to run a for-each loop on a collection, the library goes "oh, wait a minute, I have to clone this entire 1000-element thing before letting you iterate". This would be very slow, and prompt programmers to stop using iterators in situations when they think the performance is critical (this includes a lot of situations when performance is not actually critical, too).

On top of that, Java has no idea how to clone your elements, even if you implement Cloneable (because Cloneable is broken).

Of course you always have a choice of cloning a collection yourself, and iterating over it for better isolation of concurrently running processes. However, in this situation the programmer needs to make the decision to pay for such isolation, which is different from the library making this decision for him.

Upvotes: 5

Related Questions