java边遍历边删除的问题(ConcurrentModificationException异常)

为什么java边遍历边删除会报ConcurrentModificationException异常呢?
请参考这个Java集合中常见checkForComodification()方法的作用?还有 modCount 和 expectedModCount 作用?


增强循环 使用迭代器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* 使用迭代器
* (不推荐使用 users.remove() 继续循环List时会报ConcurrentModificationException)
*/
public static void list(){
List<User> users = getUsers();
Iterator<User> iterator = users.iterator();
while (iterator.hasNext()){
//删除判断条件
if (iterator.next().getId()>0 && iterator.next().getId()<3){
iterator.remove();
}
}
for (User user:users){
System.out.println(user.getName());
}
}
/**
* 使用迭代器
*/
public static void set(){
Set<User> users = getSetUsers();
Iterator<User> iterator = users.iterator();
while (iterator.hasNext()){
//删除判断条件
if (iterator.next().getId()>0 && iterator.next().getId()<3){
iterator.remove();
}
}
for (User user:users){
System.out.println(user.getName());
}
}

Powered by Hexo

Copyright © 2016 - 2019 When I think of you, I smile. All Rights Reserved.

UV : | PV :