Home java Why in java 2 interfaces: Iterable and Iterator?

Why in java 2 interfaces: Iterable and Iterator?




In my opinion, they only contribute to confusion. I understand their role: Iterable says that according to class objects, in principle, it is possible to content, and the ITERATOR sets the methods themselves for content. But in my opinion, all this perfectly looked in the same interface. Which would declare the class icing and at the same time asked methods for content.

Answer 1, Authority 100%

It would be possible to think about it if the estimated conformity of ITERABLE and its ITERATOR It was “one to one” . But the situation is different: ITERABLE Maybe a few more ITERATOR immediately (perhaps also in different Threads!). That is, these are interfaces representing two different entities: Collection and bypass collection .

Already it is necessary to divide them, because otherwise, for several parallel traverses, the collection should be always cooked into the iterator and have two types of copying (for iterator and for the collection), and here it is already viewed explicit violation. SRP (SINGLE RESPONSIBILITY PRINCIPLE, Single Principle Responsibilities ) .

Answer 2, Authority 15%

One – the one who goes. This is iterator
The other is one comes. This is Iterable

The first is not possible without a second. The second is possible without the first, but useless.

And in fact, iteble is just a way to set a standard mechanism for extracting an iterator. It is not so important in the iteration. It is not needed at all.
For example, List has another ListIterator, to which the ITERABLE does not have any relationship at all. Nevertheless, this is a real iterator and even exemplated with additional features.

Answer 3

… All this would be great in one interface

did not look.

ITERATOR – This is interface. That is, we can call the method of some class, transfer it the iterator and how to say: “Here is a certain sequence, run in it and make a number of actions.”

Thanks to the abstractness, the iterator can not be attached at all any collection, and independently generate values ​​on the fly!

And these actions associated with the sequential passage by items are the same for any type of container.

But even if we assume that any iterator is tied to its container, it still turns out not good. Iterator is an auxiliary entity whose state must be stored. Plus, how correct noticed @ d-side , iterator even the level of perception is a separate entity.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions