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 {

/**

* Returns an iterator over a set of elements of type T.

*

* @return an Iterator.

*/

Iterator iterator();

}

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

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

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

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

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

制定自己的 迭代器实现!

AbstractList 源码实现:

public abstract class AbstractList extends AbstractCollection implements List {

/**

* Sole constructor. (For invocation by subclass constructors, typically

* implicit.)

构造函数

protected AbstractList() {

}

实现 Iterable 接口的方法,

public Iterator iterator() {

return new Itr();

}

内部类 定义自己的 迭代器的 具体实现

private class Itr implements Iterator {

/**

* Index of element to be returned by subsequent call to next.

*/

当前索引

int cursor = 0;

/**

* Index of element returned by most recent call to next or

* previous. Reset to -1 if this element is deleted by a call

* to remove.

*/

上一次的索引位置

int lastRet = -1;

/**

* The modCount value that the iterator believes that the backing

* List should have. If this expectation is violated, the iterator

* has detected concurrent modification.

*/

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();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值