iterator remove_了解Iterator

在学Java集合框架的集合类的时候偶然看到使用Iterator遍历集合,感觉代码很简单,就去了解了下。

Iterator,迭代器,它提供了对一个容器对象中的各个元素进行访问,而又不暴露该容器对象的内部细节的一种方法。

Java集合框架的集合类,我们也称之为容器。容器有很多种,比如ArrayList,linkedList,HashSet……每种容器都有其特点,ArrayList底层是一个动态数组,LinkedList是双链表结构,HashSet依赖的是哈希表,每种容器都有其特有的数据结构。

而正是由于容器的内部结构不同,我们有时可能并不知道该如何去遍历一个容器中的元素,为了使对容器内元素的操作更为简单,于是就有了迭代器(Iterator)。

一般我们对于容器的遍历:

8f47bc4d83af4528212f0bd65e8829e5.png
对数组使用下标来进行遍历处理

ba89f70040837003ab41a8c78bfa011a.png
对ArrayList的遍历由get方法得到

对于这两种遍历方式,我们都知道它的内部结构,访问代码和集合本身是紧密耦合的,无法将访问逻辑从集合类和客户端代码中分离出来。不同的集合会对应不同的遍历方法,客户端代码无法复用。在实际应用中如何将上面两个集合整合是相当麻烦的,所以才有了Iterator,他总是用一种逻辑来遍历集合,使得客户端自身不需要和集合进行打交道,而是控制Iterator向它发送向前向后指令,就可以遍历集合。

1,Iterator:

那么在Java中的Iterator接口是如何实现的呢?

在JDK中它是这样定义的:

73a250e5f35c6dcb1edbc99df9942dc9.png

对collection进行迭代的迭代器。迭代器取代了Java Collection Framework中的Enumeration。迭代器和枚举有两点不同:1,迭代器在迭代期间可以从集合中移除元素;2,方法名得到了改进。

Iterator接口定义如下:

public interface Iterator<E> {

boolean hasNext();//判断是否存在下一个对象元素

E next();//获取下一个元素

default void remove() {//移除元素

throw new UnsupportedOperationException("remove");}

default void forEachRemaining(Consumer<? super E> action) {

Objects.requireNonNull(action);

while (hasNext())

action.accept(next());

}

}

2,Iterable:

Java中还提供了一个Iterable接口,该接口实现后返回的是一个迭代器,实现了该接口的子接口有:

1def5ac097aa03d4f0e9938c63aa8699.png

实现Iterable接口允许对象称为Foreach语句的目标。就可以通过foreach语句来遍历底层序列。

Iterable接口定义如下:

public interface Iterable<T> {

Iterator<T> iterator();

default void forEach(Consumer<? super T> action) {

Objects.requireNonNull(action);

for (T t : this) {

action.accept(t);

}

}

default Spliterator<T> spliterator() {

return Spliterators.spliteratorUnknownSize(iterator(), 0);

}

}

使用迭代器进行遍历集合的例子:

ba8fcf1467cef2cdaeeff6ad72cffbd3.png
ArrayList使用迭代器遍历

71c324ba4a49a027f2cd12d9c80af37f.png
LinkedList使用迭代器遍历

使用foreach遍历集合:

b489fec278167da5d28df051c18387a6.png

可以看出,使用foreach遍历集合的优势在于代码更加简洁,更不容易出错,不用关心下标的起始值和终止值。

3,Iterator遍历时不可以改变集合问题:

在使用Iterator的时候不能对所遍历的容器进行改变其大小结构的操作。例如在使用Iterator进行迭代时,如果对集合进行add、remove操作就会出现异常,如下:

64ae1eeb815c3c07857051e1e7a2a854.png
使用ArrayList的remove方法改变ArrayList

847777f14d5b3d7c56c15b502c7d48a3.png
抛出ConcurrentModificationException异常

在ArrayList源码中可以看到Iterator的实现源码

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;

public boolean hasNext() {

return cursor != size;

}

@SuppressWarnings("unchecked")

public E next() {

checkForComodification();

int i = cursor;

if (i >= size)

throw new NoSuchElementException();

Object[] elementData = ArrayList.this.elementData;

if (i >= elementData.length)

throw new ConcurrentModificationException();

cursor = i + 1;

return (E) elementData[lastRet = i];

}

public void remove() {

if (lastRet < 0)

throw new IllegalStateException();

checkForComodification();

try {

ArrayList.this.remove(lastRet);

cursor = lastRet;

lastRet = -1;

expectedModCount = modCount;

} catch (IndexOutOfBoundsException ex) {

throw new ConcurrentModificationException();

}

}

@Override

@SuppressWarnings("unchecked")

public void forEachRemaining(Consumer<? super E> consumer) {

Objects.requireNonNull(consumer);

final int size = ArrayList.this.size;

int i = cursor;

if (i >= size) {

return;

}

final Object[] elementData = ArrayList.this.elementData;

if (i >= elementData.length) {

throw new ConcurrentModificationException();

}

while (i != size && modCount == expectedModCount) {

consumer.accept((E) elementData[i++]);

}

// update once at end of iteration to reduce heap write traffic

cursor = i;

lastRet = i - 1;

checkForComodification();

}

final void checkForComodification() {

if (modCount != expectedModCount)

throw new ConcurrentModificationException();

}

}

通过查看源码可以发现,检查并抛出异常的是checkForComodification() 方法。在ArrayList中,modCount是当前集合的版本号,每次修改集合都会加1;而expectedModCount是当前迭代器的版本号,在迭代器实例化时 int expectedModCount = modCount;,而在checkForComodification() 方法中就是验证modCount和expectedModCount是否相等。当我们调用了ArrayList的add()或remove()时,会更新modCount,而expectedModCount不变,所以下回导致再次调用next()方法的时候抛出异常。而为什么使用Iterator.remove()没有问题呢?我们可以由源代码看出,在Iterator的remove()方法中同步了expectedModCount的值,所以不会抛出异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值