gpt4 book ai didi

java - 尝试从列表中删除元素时出现 ConcurrentModificationException

转载 作者:行者123 更新时间:2023-12-01 22:28:29 24 4
gpt4 key购买 nike

嗯,我已经阅读了其他帖子,但无法解决我的问题。我的 ManagedBean 中有一个 dataTable (JSF) 绑定(bind)。我有一个选定元素的列表,我想删除这些元素,请参阅:

public void removeSelected() {

for (Map.Entry<Integer, Boolean> entry : registrosSelecionados.entrySet()){
if (entry.getValue() == true){
int id = entry.getKey();
Iterator<Bean> it = beans.iterator();
while(it.hasNext()){
Bean b = it.next();
if (b.getId().equals(id)){
setBean(b);
deletar();
}
}
}
}
}

我上面的方法调用了另一个名为“deletar()”的方法,请参阅:

 public void deletar() {
try {


//Se o bean for nulo então capturamos o bean selecionado no DataTable, se este existir
if (bean == null){
if (dataTable == null){
throw new RuntimeException("O bean é nulo e não há dataTable vinculado ao ManagedBean. A deleção será abortada");
}
bean = (Bean) dataTable.getRowData();
}

beforeRemove();
getBoPadrao().delete((AbstractBean) bean);
addInfoMessage("Registro deletado com sucesso");
beans.remove(bean);
bean = null;
afterRemove();
} catch (BOException e) {
addErrorMessage(e.getMessage());
FacesContext.getCurrentInstance().validationFailed();
} catch (Exception e) {
e.printStackTrace();
logger.error((new StringBuilder()).append("Erro ao deletar: ")
.append(e.getMessage()).toString());
FacesContext.getCurrentInstance().validationFailed();
addErrorMessage((new StringBuilder()).append("Erro ao deletar. ")
.append(e.getMessage()).toString());
}
}

Bean 已从数据库中删除,但是当尝试从“列表”中删除时出现错误:

Jan 31, 2015 5:38:32 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
Grave: java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at br.com.jwebbuild.mb.BasicCrudMBImpl.removeSelected(BasicCrudMBImpl.java:226)

编辑1

我尝试编辑我的 deletar() 方法,放置一个迭代器来删除元素,但没有成功,错误仍然存​​在。

public void deletar() {
try {


//Se o bean for nulo então capturamos o bean selecionado no DataTable, se este existir
if (bean == null){
if (dataTable == null){
throw new RuntimeException("O bean é nulo e não há dataTable vinculado ao ManagedBean. A deleção será abortada");
}
bean = (Bean) dataTable.getRowData();
}

beforeRemove();
getBoPadrao().delete((AbstractBean) bean);
addInfoMessage("Registro deletado com sucesso");

Iterator<Bean> it = beans.iterator();
while (it.hasNext()) {
Bean b = it.next();
if (b.equals(bean)) {
it.remove();
}
}

bean = null;
afterRemove();

最佳答案

你说,

Well, i already read the others posts and can't solve my problem.

如果您阅读过其他类似的文章,那么您应该已经知道您只能使用迭代器进行删除,这是您没有做的事情,而这正是您必须做的。

例如,

public void deltar(Iterator<Bean> it, Bean bean) {
// .....
it.remove();
}

关于java - 尝试从列表中删除元素时出现 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28256346/

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