gpt4 book ai didi

java - 迭代时删除和添加对象到列表

转载 作者:行者123 更新时间:2023-11-29 10:00:24 26 4
gpt4 key购买 nike

我试图从列表中删除对象,但出现以下异常:

failure:java.util.ConcurrentModificationException null

这就是我尝试从列表中删除对象的方式:

private List<testVO> removeDuplicateEntries(List<testVO> sessionList,List<testVO> dbList){


for (Iterator<testVO> dbIterator = dbList.listIterator(); dbIterator.hasNext(); ) {
testVO voDB = dbIterator.next();

for (Iterator<testVO> sessionIterator = sessionList.iterator(); sessionIterator.hasNext();) {
testVO voSession = (testVO) sessionIterator.next();

if(voDB.getQuestionID().intValue() == voSession.getQuestionID().intValue()){
//remove the object from sesion list
sessionIterator.remove();
//Add the object from DB to session list
sessionList.add(voDB);
}

}

}

return sessionList;
}

我想删除当前在 sessionList 中的重复项,并添加 dbList 中的重复项。

最佳答案

您不能在遍历它时添加到 sessionList。

    for (Iterator<testVO> dbIterator = dbList.listIterator(); dbIterator.hasNext(); ) {
testVO voDB = dbIterator.next();

List<testVO> toBeAdded = new LinkedList<>();
for (Iterator<testVO> sessionIterator = sessionList.iterator(); sessionIterator.hasNext();) {
testVO voSession = (testVO) sessionIterator.next();

if(voDB.getQuestionID().intValue() == voSession.getQuestionID().intValue()){
//remove the object from sesion list
sessionIterator.remove();
//Add the object from DB to session list
//CANNOT DO: sessionList.add(voDB);
toBeAdded.add(voDB);
}
}
Collections.addAll(sessionList, toBeAdded);
}

关于java - 迭代时删除和添加对象到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32947202/

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