public interface Iterator<AnyType>{
boolean hasNext();
AnyType next();
void remove();
}
上下两行代码来自Java源码
public interface Iterable<T>{
//返回一个Iterator
Iterator<T> iterator();
default void forEach(){
...
}
...
}
Iterable接口内部声明抽象方法iterator(),返回一个迭代器——二者可以理解为包含关系,即Iterable接口中包含了Iterator接口。
Collection继承了Iterable接口,所以可以生成Iterator对象对集合进行简单遍历。(Iterator接口中的方法有限,所以只能进行简单的遍历)
public static <AnyType> void print(Collection<AnyType> col){
Iterator it = col.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}