简体   繁体   中英

Questions about Iterator Interface

i'm studyng the basic interface and classes of the Java.util package. Now the interface Set is a subclass of Collection and Iterable, so Set have the Iterator moudle. So why i use a reference of the Iterator Interface?

    Iterator<String> iterx = x.iterator();

Iteratr is also a interface. But i haven't see any relation about the Iterable interface and the Iterator interface. Iterable have a moudle that is named Iterator. it would not be more correct to write

Iterable.Iterator iterx = x.iterator();

Because x.iterator call the moudle that Set have inherited by Iterable, and don't call the Iterator interface.

What i don't have understand?

The Iterable interface says that a particular Collection is iterable, which means you can iterate over it by using Iterator.

It has only one method, which is iterator() returns an Iterator. Any collection eg List which implements Iterable provides implementation of iterator() method.

Iterator is also an interface which defines the iteration process it provides next(), hasNext() and remove() method which can be used to control the iteration, access the element and remove it.

You use Iterator<String> for the same reason you use String in

String stringx = x.toString()

the method (correct name for "module") declares that it returns you an object of that type. Methods can return any unrelated type and you'll have to adjust and use the variable type they give you.

Iterator is conceptually related to Iterable but they don't inherit from each other or so. And it's actually just convention that the Iterator grants you access to the same data as the Iterable that produced it.

But the design / convention for Iterator is that you can iterate once in the lifetime of an iterator over the collection of items (repeating hasNext() ? Ok give next() ! over and over until there is no next.). If you want to iterate again you'll have to get a fresh Iterator . And that's the responsibility of Iterable : It can produce a fresh Iterator every time you ask it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM