java.util.ConcurrentModificationException not thrown when expected(java.util.ConcurrentModificationException 未按预期抛出)
问题描述
以下代码抛出 java.util.ConcurrentModificationException,正如预期的那样:
The following code throws a java.util.ConcurrentModificationException, as expected:
public void test(){
ArrayList<String> myList = new ArrayList<String>();
myList.add("String 1");
myList.add("String 2");
myList.add("String 3");
myList.add("String 4");
myList.add("String 5");
for(String s : myList){
if (s.equals("String 2")){
myList.remove(s);
}
}
}
但是,以下代码不会抛出异常,而我希望它会被抛出:
However, the following code does not throw the Exception, while I expect it to be thrown:
public void test(){
ArrayList<String> myList = new ArrayList<String>();
myList.add("String 1");
myList.add("String 2");
myList.add("String 3");
for(String s : myList){
if (s.equals("String 2")){
myList.remove(s);
}
}
}
区别在于第一个列表包含5个项目,而第二个列表包含3个.使用的JVM是:
The difference is that the first list contains 5 items, while the second list contains 3. The JVM used is:
java version "1.8.0"
Java(TM) SE Runtime Environment (build 1.8.0-b132)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)
问题:为什么第二段代码NOT会抛出java.util.ConcurrentModificationException?
The question: why does the second piece of code NOT throw the java.util.ConcurrentModificationException?
推荐答案
在实现中从 ArrayList.iterator()
返回的迭代器显然都在调用中仅使用检查结构修改next()
,not 在对 hasNext()
的调用中.后者看起来像这样(在 Java 8 下):
The iterator returned from ArrayList.iterator()
in the implementation we're apparently both using only checks for structural modification in calls to next()
, not in calls to hasNext()
. The latter just looks like this (under Java 8):
public boolean hasNext() {
return cursor != size;
}
所以在你的第二种情况下,迭代器知道"它返回了两个元素,并且列表只有 两个元素......所以 hasNext()
只是返回 false,我们永远不会第三次调用 next()
.
So in your second case, the iterator "knows" that it's returned two elements, and that the list only has two elements... so hasNext()
just returns false, and we never end up calling next()
the third time.
我认为这是一个实现细节 - 基本上检查没有尽可能严格.在这种情况下,hasNext()
执行检查并抛出异常也是完全合理的.
I would view this as an implementation detail - basically the checking not being as strict as it could be. It would be entirely reasonable for hasNext()
to perform a check and throw an exception in this case too.
这篇关于java.util.ConcurrentModificationException 未按预期抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:java.util.ConcurrentModificationException 未按预期抛出
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01