2014-05-30 61 views
0
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中使用Iterator,而不是增强的for-loop,但是这也没有帮助。我真的只需要将约会设置为true的那部分工作,checkRemoval似乎在实现布尔解析更改之前提前工作。任何帮助将不胜感激,谢谢。从集合中删除项目/对象的更改字段

+0

你可以使用迭代器发布代码 –

+2

我认为你的问题不是使用resolve = true的设置,而是使用checkRemoval方法。循环播放时无法修改列表。要么将原始列表的副本放到其他列表中,并从那里开始工作 – vikeng21

回答

1

我愿意打赌,你说这是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() 
    } 
+0

也要感谢您的评论。我显然是在尝试从列表中删除项目,同时遍历它。问题解决了,非常感谢! –

1

的ConcurrentModification抛出异常,使用for循环,其中收集得到修改。所以这个问题不一定是你发布的代码。您可能正在调用此函数的appts List上进行循环。发布更多的代码可能会有所帮助。

+0

好吧,我看到...完美的我得到它工作..切换回到迭代器的方法,并改变了我所谓的位置,现在它的工作..谢谢mucho! –