简体   繁体   中英

Use of the Iterable and Iterator interface

I am still quite new to Java and today I try to understand the use of iterators.
So I have a few questions:

  1. Why would I need to implement Iterable at all, it only gives a method to create a new iterator for a collection, but I could just as well use a normal, or enchanced for-loop if I wanted to get all elements. I already read this question: What is the Iterable interface used for? and much more, but they kind of just say that it allows you to iterate through all your elements, which leads back to my question.

  2. If I implement Iterable, should I implement Iterator too?
    Because this one actually provides methods that could be useful to overwrite.
    For example if my class had a boolean whether I want my objects in a loop or not, I could write

     public boolean hasNext() { if(loop) return true; //other things } 
  3. If I do like said in 2., will an enchanced for-loop use these overwritten methods?
    For example with the mentioned loop attribute above: Would the for-loop run infintely if it was true?

I hope someone can help me better understand this whole concept.

If you are defining a collection, you are implementing an Iterable . For example, if you want to create a custom list, you will typically make it subclass AbstractList , which itself extends AbstractCollection , which implements Collection , which implements Iterable . So your list will be "de facto" an Iterable .

But if you subclass AbstractList , you won't have to implement the iterator yourself, since this method would already be implemented there. That said, you may want to provide a specialized iterator for your needs.

When you implement Iterable (if you really want to), you return an Iterator . The collection itself should not implement Iterator , only the returned iterator. Look at the AbstractList source, for an example to see how it is done.

When you are using an enhanced for-loop, you ARE using an Iterable . An enhanced for loop is just syntactic sugar for a loop on the iterator returned by iterator() . It means the compiler transforms your code to use the iterator. This is why you have to implement Iterable for the collection to be used in an enhanced for-loop.

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