gpt4 book ai didi

java - 从列表中删除对象 - ConcurrentModificationException

转载 作者:行者123 更新时间:2023-12-01 23:11:03 25 4
gpt4 key购买 nike

我有这个代码:

public static void main(String[] args) {
User user = new User("user1","user1",1l);
User user1 = new User("user2","user2",2l);
User user2 = new User("user3","user3",3l);

List<User> list = new ArrayList<User>();
list.add(user);
list.add(user1);
list.add(user2);

for(User user3 : list){
System.out.println(user3.getName());
if(user3.getName().equals("user1")){
list.remove(user3);
}
}
}

执行此代码时,出现以下错误:

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)

如何避免它?

最佳答案

使用Iterator迭代列表,然后使用Iterator.remove()删除特定元素

关于java - 从列表中删除对象 - ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21973342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com