java vector iterator_java – 为什么Vector方法Iterator和ListIterator快...

if the Vector is structurally modified at any time after the Iterator is created, in any way except through the Iterator’s own remove or add methods, the Iterator will throw a ConcurrentModificationException.

这是一个例子:

import java.util.*;

public class Test {

public static void main(String[] args) {

List strings = new Vector();

strings.add("lorem");

strings.add("ipsum");

strings.add("dolor");

strings.add("sit");

int i = 0;

Iterator iter = strings.iterator();

while (iter.hasNext()) {

System.out.println(iter.next());

// Modify the list in the middle of iteration.

if (i++ == 1)

strings.remove(0);

}

}

}

输出:

lorem

ipsum

Exception in thread "main" java.util.ConcurrentModificationException

at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)

at java.util.AbstractList$Itr.next(AbstractList.java:343)

at Test.main(Test.java:18)

该计划执行以下操作:

>创建一个Vector并获取一个迭代器

>两次调用next().

>修改矢量(通过删除第一个元素)

>再次调用next()(在向量被修改之后)

>这会导致抛出ConcurrentModificationException.

由于Java的for-each循环依赖于迭代器,因此这些构造也可能抛出ConcurrentModificationExceptions.解决方案是在迭代之前制作列表的副本(所以你迭代一个副本)或使用例如像这样的CopyOnWriteArrayList:

import java.util.*;

import java.util.concurrent.CopyOnWriteArrayList;

public class Test {

public static void main(String[] args) {

List strings = new CopyOnWriteArrayList();

strings.add("lorem");

strings.add("ipsum");

strings.add("dolor");

strings.add("sit");

int i = 0;

Iterator iter = strings.iterator();

while (iter.hasNext()) {

System.out.println(iter.next());

// Modify the list in the middle of iteration.

if (i++ == 1)

strings.remove(0);

}

}

}

输出:

lorem

ipsum

dolor

sit

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值