Iterator & Iterable

Source: Internet
Author: User
Tags iterable

One

The

java.lang.Iterable
Java.util.Iterator

Iterator is an iterator class, and iterable is an interface.
Many classes implement the Iterable interface so that an object can call the iterator () method.
is generally used in conjunction, such as the
HashMap class to implement the Iterable interface, and to access or print out all the contents of the map, you can: HashMap HashMap;
Iterator iter = Hashmap.iterator ();
while (Iter.hashnext ()) {
  String s = iter.next ();
}

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

      1, 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 to reset the current iteration position.
      But in this case, collection can only have one current iteration position at a time.
      iterable Otherwise, each call will return an iterator that counts from the beginning.
      Multiple iterators are non-disruptive.

2. Enable the object to traverse through foreach.

Iterator & Iterable

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.