Definition of iterable:
Java.lang Bag
/** * Implementing this interface allows a object to be the target of * the "foreach" statement. * * @param <T> The type of elements returned by the iterator * * @since 1.5 */public interface iterable<t> {
/** * Returns An iterator over a set of elements of type T. * * @return an Iterator. * /iterator<t> Iterator ();}
Definition of iterator:
Java.util Package:
Public interface Iterator<e> { boolean hasnext (); E next (); void Remove ();
Iterator is an iterator class, and iterable is designed to iterate using foreach as long as the interface is implemented.
The iterator interface is encapsulated in iterable, and the iterator iterator can be used as long as the class that implements the Iterable interface is implemented.
Collections collection, List, and set are iterable implementation classes, so they and their subclasses can iterate using foreach.
So why don't these collection classes directly implement iterator?
Iterator and Core methods next (), Hasnext (), remove (), are dependent on the current position, and if these collections are implemented directly iterator, you must include a pointer to the current iteration position. When a collection is passed between methods, the value after next () is not known because the current position is unknown. When implementing iterable, however, each invocation returns an iterator from the beginning, each of which does not affect each other.
The difference between iterator and iterable in Java