Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: why are iterators not copyable

I would think that Iterator.copy() would be quite a handy function. You could implement iterator filters in a much better way.

For example, the only reason in Googles Java Collection for the filter (and similar) functions to use UnmodifiableIterator (which is just an Iterator without remove) is because you cannot implement such a filter Iterator otherwise without being able to copy it at some point. (Really, that is not possible with the current interface; try yourself.)

Another advantage would be that you could use an iterator in a for-each-loop: Because a copy-able iterator would automatically also be iterable. See also this question. Right now, the main design reason to not allow this is because an Iterator which implements Iterable and Iterator<T> iterator() { return this; } would invalidate the iterator. By having a copy function, it is as simple as Iterator<T> iterator() { return copy(); } and it would not invalidate the original iterator. Thus there is no reason anymore to not allow this.

Is there any reason? Just to make it less complicated to implement it?

like image 941
Albert Avatar asked Sep 30 '10 15:09

Albert


People also ask

Are iterators copyable?

You can only iterate an Iterator once. If you need to "reset" it, and recreating the Iterator is expensive (such as reading from a file), you could copy the data into a temporary Collection (such as an ArrayList). But that requires enough memory to hold everything at once.

Why are iterators considered lazy?

In fact, many iterators calculate their values one at a time, as they are needed. Each time you request the next item, the iterator will calculate it there and then. This is called lazy evaluation – the iterator doesn't do any work until it absolutely has to.

Why do iterators have no add method?

The sole purpose of an Iterator is to enumerate through a collection. All collections contain the add() method to serve your purpose. There would be no point in adding to an Iterator because the collection may or may not be ordered (in the case of a HashSet ).

Are iterators thread safe Java?

Iterators are still not threadsafe. The solution to this iteration problem will be to acquire the collection's lock when you need to iterate over it, which we'll talk about in a future reading.


1 Answers

Although they usually are, Iterators do not theoretically have to be linked to a collection. The copy method over an input stream, for instance, would be difficult to implement, and would very easily cause obscure memory problems.

like image 106
ILMTitan Avatar answered Oct 19 '22 07:10

ILMTitan