CopyOnWriteArrayList[/color]<String> al = new CopyOnWriteArrayList<String>();
al.add("ok1");
al.add("ok2");
al.add("ok3");
sop(al);
//Iterator it = al.iterator();
Iterator<String> it = al.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj.equals("ok2")) {
al.add("ok4");
//it.remove();
al.remove("ok4");
}
sop(obj);
}
sop(al);
}
}
复制代码
这样改的话就没问题了,普通集合列表(ArrayList)不可以并发操作,而CopyOnWriteArray这个类是jdk1.5增加的并发集合类,可以执行并发操作,即可以在遍历集合列表的过程中对集合列表进行增加和删除操作。代码中用it.remove()达到删除集合列表最后一个元素的目的,是不可取的,查看API文档:Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.大概意思是说:在iterator执行的过程中,用iterator来删除集合列表最后一个元素的结果是不确定的,可能会抛出异常 java.lang.UnsupportedOperationException,而如果改为al.remove("ok4")就没问题了。作者: 孙飞 时间: 2012-7-4 23:09