Package Java.lang;
Import Java.util.Iterator;
Public interface Iterable<t> {
Iterator<t> Iterator ();
}
Iterable is located in the Java.lang package, which holds a iterator reference
Package java.util;
Public interface Iterator<e> {
Boolean hasnext ();
E next ();
void Remove ();
}
Iterator is also an interface that contains three methods, Hasnext, Next, remove
Public Interface extends iterable<e> {}
Java.util.Collection inherits from Java.lang.Iterable, why does the JDK author design This, why does the collection interface not inherit directly from iterator?
In fact, this is also a design pattern: iterator design mode
Why this design, if collection directly from the iterator inheritance, then the collection implementation class must be directly implemented Hasnext, next, remove method.
1. This can lead to code confusion, the iterative code is confused with the implementation code of the collection itself, resulting in reading difficulties, and there are methods to repeat, such as remove, can not be separated from the implementation of the iteration
2. The current cursor pointer must be included in the collection implementation class, and processing is quite awkward when concurrency
3. The interface is not unified, collection inherit from the Iterable, in the iteration only need to get its iterator (internal class implementation), with a unified object iteration, and multiple iterators can do non-interference
The iterable and iterator of Java.util