[英]Removing Item from Collection / Changing field of Object
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);
}
}
是公然的并发修改。 在循环中循环访问集合时,不能从集合中删除元素。 相反,您需要使用迭代器 :
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()
}
使用for循环引发ConcurrentModification异常,在该循环中修改Collection。 因此,问题不必是您发布的代码。 您可能正在调用此函数的appts列表上有一个循环。 发布更多代码可能会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.