public void searchOwner(List<Appointments> appts, String owner) {
Appointments theOne = null;
for (Appointments temp : appts) {
if (owner.equalsIgnoreCase(temp.owner.name)) {
System.out.println(temp.data);
temp.setResolved(true);
}
}
}
public void checkRemoval() {
for (Appointments appts : appointments) {
if (appts.resolved == true) {
appointments.remove(appts);
}
//Iterator method used before enhanced for-loop
public void checkRemovalI(){
Iterator<Appointments> it = appointments.iterator();
while(it.hasNext()){
if(it.next().resolved = true){
it.remove();
}
}
}
到目前为止,这是我遇到问题的地方。我正在尝试检查约会的arrayList,并查看该字段(已解决)是否设置为true,但是在尝试将resolve =设置为true时,我在searchOwner方法期间收到了ConcurrentModification异常。我试过在checkRemoval中使用迭代器,而不是增强的for循环,但是也没有帮助。我真的只需要获得将约会设置为true的部分即可工作,在实现更改后的布尔值解析之前,checkRemoval似乎早在工作。任何帮助将不胜感激,谢谢。
最佳答案
我敢打赌,并不是说ConcurrentModificationException
是在您所说的地方引起的,而是在checkRemoval()
中引起的,您可能会在提到将resolved
设置为true的那行之前调用它。混乱。
我之所以这样说是因为:
for (Appointments appts : appointments) {
if (appts.resolved == true) {
appointments.remove(appts);
}
}
是公然的并发修改。在循环中循环访问集合时,不能从集合中删除元素。相反,您需要使用iterator:
public void checkRemoval() {
Iterator<Appointment> apptsIterator = appointments.iterator();
while (apptsIterator.hasNext()){
if (appts.next().resolved == true)
apptsIterator.remove(); //removes the last element you got via next()
}