Java iterator iterators and iterable interfaces

Source: Internet
Author: User
Tags iterable

Java.lang.Iterable
Java.util.Iterator

Iterator is an iterator class, and iterable is an interface.
Many classes implement the Iterable interface so that the object can call the iterator () method.
are generally used in combination, such as
The HashMap class implements the Iterable interface, and when you want to access or print all the contents of a map, you can:

1 HashMap (); 2 Iterator iter =3while4   String s =5

Why do you have to implement Iterable interface, why not directly implement iterator interface?
Look at the collection classes in the JDK, such as the list family or set family, are implemented Iterable interface, but do not directly implement the iterator interface.
It makes sense to think carefully about it.

Because the core method of the Iterator interface next () or Hasnext () is dependent on the current iteration position of the iterator.
If collection implements the iterator interface directly, it is bound to cause the collection object to contain the data (pointers) of the current iteration position.
When a collection is passed between different methods, the result of the next () method becomes unpredictable because the current iteration position is not pre-provisioned.
Unless you add a reset () method to the iterator interface, you can reset the current iteration position.
But in this case, collection can only have one current iteration position at a time.
Instead, Iterable returns an iterator that counts from the beginning of each call.
Multiple iterators are non-interfering.

Java iterator iterators and iterable interfaces

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.