天天看点

java中集合和迭代器_集合 java中的迭代器

今天学习了 集合,但是感觉对于迭代器不是 很明白,所以研究了一下!

在 JDK中

Collection作为集合的顶级容器, 她实现了Java.lang.Iterable  接口!

Iterable:  可迭代的, 想使用迭代功能的容器必须实现这个顶级接口,中的 iterator() 方法。

Iterator:迭代器. 每个容器的内部都有不同的迭代器实现。抽取出她们的共性,我们抽取出

Iterator 接口。

我们查看源码

Iterator:

public interface Iterator {

boolean hasNext();

E next();

void remove();

}

Iterable:

public interface Iterable {

Iterator iterator();

}

下面我们分析一下 迭代器 是 如何实现的?

1 如果AbstractList 类,要使用迭代器。 她必须实现 Iterable.

2 在AbstractList 代码中必须实现 Iterator iterator(){};

返回 迭代器的接口或子类 引用。

2  在   AbstractList 代码中,定义一个内部类,实现 Iterator 接口。

制定自己的 迭代器实现!

AbstractList 源码实现:

当前索引

int cursor = 0;

上一次的索引位置

int lastRet = -1;

int expectedModCount = modCount;

判断是否 有下一个元素

public boolean hasNext() {

return cursor != size();

}

获取下一个元素

public E next() {

checkForComodification();

try {

int i = cursor;

E next = get(i);

lastRet = i;

cursor = i + 1;

return next;

} catch (IndexOutOfBoundsException e) {

checkForComodification();

throw new NoSuchElementException();

}

}

去掉元素

public void remove() {

if (lastRet < 0)

throw new IllegalStateException();

checkForComodification();

try {

AbstractList.this.remove(lastRet);

if (lastRet < cursor)

cursor--;

lastRet = -1;

expectedModCount = modCount;

} catch (IndexOutOfBoundsException e) {

throw new ConcurrentModificationException();

}

}

检查异常

final void checkForComodification() {

if (modCount != expectedModCount)

throw new ConcurrentModificationException();

}

}

}