Iterator和Iterable区别
public abstract Iterator iterator();
public Iterator<E> iterator() {
返回一个迭代器对象,这个对象的实现类继承了Iterator接口
public abstract boolean hasNext();
public abstract Object next();
public abstract void remove();
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
// prevent creating a synthetic constructor
@SuppressWarnings("unchecked")
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
throw new ConcurrentModificationException();
return (E) elementData[lastRet = i];
throw new IllegalStateException();
ArrayList.this.remove(lastRet);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int size = ArrayList.this.size;
final Object[] es = elementData;
throw new ConcurrentModificationException();
for (; i < size && modCount == expectedModCount; i++)
action.accept(elementAt(es, i));
// update once at end to reduce heap write traffic
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
for(Iterator iterator = list.iterator(); iterator.hasNext(); System.out.println(i)){
(只要实现了Iterable接口,就可以直接使用foreach)


浙公网安备 33010602011771号