gpt4 book ai didi

java - 使用迭代器 - java.util.ConcurrentModificationException

转载 作者:行者123 更新时间:2023-11-29 04:13:25 25 4
gpt4 key购买 nike

所以,这让我回来了

java.util.ConcurrentModificationException

并指向 System.out.println 行

Iterator<Autor> it = autores.iterator(); 
// Declaring a class iterator

public void listarAutores() {

while (it.hasNext()) {
String aux = it.next().getNomeCompleto();
// Get string from Class Autor method
System.out.println(aux);
// Printing that string
}
}

为什么会这样,我该如何解决?

最佳答案

如果您在两次调用该方法之间修改集合,就会发生这种情况。例如:

listarAutores();
autores.add(anotherAuthor);
listarAutores();

您应该在每次调用时在方法中创建一个新的迭代器,或者更好的是,根本不使用迭代器:

public void listarAutores() {
for (Author a : autores) {
String aux = a.getNomeCompleto();
// Get string from Class Autor method
System.out.println(aux);
// Printing that string
}
}

关于java - 使用迭代器 - java.util.ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53746494/

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