The difference between Iterator and Iterable in java

Iterator is an iterator class (in fact, it is also an interface in javaAPI), and Iterable is an interface. 
Many classes implement the Iterable interface so that objects can call the iterator() method (which returns an Iterator object). 
It is generally used in combination. For example, the 
HashMap class implements the Iterable interface, and when you want to access or print out all the contents of the Map, you can do this: HashMap hashMap; 
Iterator iter = hashMap.iterator(); 
while(iter.hashNext() ) { 
  String s = iter.next(); 

 

 

 

Why must the Iterable interface be implemented, and why not directly implement the Iterator interface? 
      Take a look at the collection classes in JDK, such as the List family or the Set family, all implement the Iterable interface, but do not directly implement the Iterator interface. 
It makes sense when you think about it. 

      Because the core method next() or hasNext() of the Iterator interface depends on the current iteration position of the iterator.       If the Collection directly implements the Iterator interface, it will inevitably cause the collection object to contain the data (pointer) of the current iteration position.       When collections are passed between methods, the result of the next() method can become unpredictable because the current iteration position cannot be preset.       Unless you add a reset() method to the Iterator interface to reset the current iteration position.       But even so, the Collection can only have one current iteration position at the same time.  Not so with Iterable, where each call returns an iterator counting from the beginning.       Multiple iterators do not interfere with each other.  




     

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326477839&siteId=291194637