Iterable and Iterator of java. util, java. utiliterable
package java.lang;
import java.util.Iterator;
public interface Iterable<T> {
Iterator<T> iterator();
}
Iterable is located in the java. lang Package, which holds an 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, and remove.
public interface Collection<E> extends Iterable<E> {}
Java. util. Collection inherits from java. lang. Iterable. Why is the jdk author designed this way? Why is the Collection interface not inherited directly from Iterator?
In fact, this is also a design model: Iterator Design Model
If the Collection is directly inherited from the Iterator, the Collection implementation class must directly implement the hasNext, next, and remove methods.
1. This will cause code confusion. The iterative code and the Collection implementation code are mixed together, making reading difficult and there are repeated methods. For example, removing can not separate iteration from itself.
2. The current cursor pointer must be included in the Collection implementation class, which is quite embarrassing for concurrent processing.
3. the access interfaces are not uniform. If Collection inherits from Iterable, you only need to get its Iterator (internal class implementation) during iteration, and use unified object iteration, and multiple iterators can do not interfere with each other.