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