2014-05-30 34 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! –