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