2013-10-29 43 views
3

我的代碼導致一個錯誤,我不知道如何解決它。我嘗試了打印報表,但它甚至不會那麼做。發生如何解決java.util.ConcurrentModificationException

錯誤這裏是確切的錯誤

java.util.ConcurrentModificationException 
java.util.ConcurrentModificationException 
     at java.util.HashMap$HashIterator.nextEntry(HashMap.java:894) 
     at java.util.HashMap$KeyIterator.next(HashMap.java:928) 
     at ca.on.oicr.pinery.lims.gsle.GsleClient.getOrders(GsleClient.java:720) 

線720第二個for循環

+0

http://docs.oracle.com/javase/7/docs/api/java/ util/ConcurrentModificationException.html – OldProgrammer

+3

您正在循環遍歷'orders'元素的循環中添加'orders',這就是導致異常的原因。不要修改循環中循環的集合。同樣採用'samples'。 – Jesper

+0

當您循環播放集合時,無法修改(添加或移除)集合。您正嘗試向訂單添加訂單。你不能這樣做。 –

回答

2

如果您想要在遍歷元素時從列表中添加或移除元素,則可以使用ListIterator。這是假設你orders是一個列表

因此,您的代碼會是這個樣子 -

ListIterator<Order> it = orders.listIterator(); 

while (it.hasNext()) { 
     Order ord = it.next(); 

     if () // some condition 
     it.remove(); // This wil remove the element that we just got using the next() method 
     if () // some other condition 
     it.add(new Order()); // THis inserts the element immediately before the next call to next() 
} 
+0

在我的情況下,我會去除?我每次都創建一個Order的新實例? – user2811419

+0

如果'orders'是一個List,那麼您可以使用'ListIterator'並使用'add'方法 – Kal

+0

yes訂單是一個列表 – user2811419

1

你試圖在遍歷其內容操縱sample內容。爲了解決這類問題,請使用不可變集合,或假裝它們是。

你想要做的是在迭代samples時,用你想要的那個建立另一個集合,並修改這個其他集合而不是你原來的集合。

+0

我認爲他在樣本循環內有兩個問題'samples'和'orders',他也在改變訂單的內容。 –

+0

是的,我希望Java中的默認集合是不可變的,以防止這種行爲...(就像他們在Scala中一樣) - 我們需要更多的函數式編程概念進入我們的面向對象的方法:) – Guillaume

+0

來解決這個問題, order.add(order)在第二個forloop之外,但是在第一個第一個循環之內?會解決它嗎? – user2811419