2013-04-04 97 views
0

我有一個方法test(),其中我試圖比較兩個LinkedHashMaps彼此,並通過刪除鍵/值對,如果它在兩個LHM中找到修改其中一個映射的內容。運行此方法時,我不斷收到ConcurrentModificationException。我明白爲什麼我得到異常(因爲我試圖修改正在循環的列表)。但我不確定如何去解決這個問題。到目前爲止,我有此代碼:ConcurrentModificationException Woes

private void test() {  

LinkedHashMap<String, BigDecimal>testBene = new LinkedHashMap<String, BigDecimal>(); 
LinkedHashMap<String, BigDecimal>testDly = new LinkedHashMap<String, BigDecimal>(); 

testBene.put("ABCDEFG", BigDecimal.ZERO); 
testBene.put("BCDEFGH", BigDecimal.ONE); 
testBene.put("CDEFGHI", BigDecimal.TEN); 

testDly.put("BCDEFGH", BigDecimal.ONE); 
testDly.put("Foo", BigDecimal.TEN); 
testDly.put("Bar", BigDecimal.TEN); 

for (Entry<String, BigDecimal> beneKeySet : testBene.entrySet()) { 
    if (testDly.containsKey(beneKeySet.getKey())) { 
     for (Entry<String, BigDecimal> dlyKeySet : testDly.entrySet()) { 
      if ((dlyKeySet.getKey().equals(beneKeySet.getKey())) && 
       dlyKeySet.getValue().equals(beneKeySet.getValue())) { 
        testBene.remove(dlyKeySet.getKey()); 
      } 
     } 
    } 
} 

} 
+2

你知道,你是比較'的'==代替'.equals()'字符串?請參閱[如何比較Java中的字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – jlordo 2013-04-04 12:56:34

+0

@jlordo是的,我爲了效率而定。對不起,就像我說的那只是一個測試。 – ResourceReaper 2013-04-04 13:11:33

+0

'=='可能更有效,但對於內容相同的兩個字符串不能保證是真的。 – jlordo 2013-04-04 13:13:10

回答

1

你可以使用一個迭代器:

for (Iterator<Entry<String, BigDecimal>> it = testBene.entrySet().iterator(); it.hasNext();) { 
    Entry<String, BigDecimal> beneKeySet = it.next(); 
    if (testDly.containsKey(beneKeySet.getKey())) { 
     for (Entry<String, BigDecimal> dlyKeySet : testDly.entrySet()) { 
      if ((dlyKeySet.getKey() == beneKeySet.getKey()) && dlyKeySet.getValue() == beneKeySet.getValue()) { 
       it.remove(); 
      } 
     } 
    } 
} 
+0

這就是答案,我想我對迭代器不太擅長。我的確讀過,解決CMEx的唯一方法就是使用一個。我試圖弄清楚如何編寫代碼來做到這一點。我測試了它,它工作,現在我只需要遍歷代碼並查看原因。非常感謝你。 – ResourceReaper 2013-04-04 13:10:30

1

您無法從列表中刪除當前正在爲每個列表重複使用a。使用列表的迭代器來做到這一點。

2

不是刪除元素,而是將要刪除的鍵放入單獨的集合中。最後,遍歷其他集合,從您的地圖中刪除鍵。

或者,使用Iterator接口而不是for-each循環。這將使您能夠在迭代時使用Iterator.remove()刪除元素。

+0

與ArrayLists有類似的問題,這是解決它的方法。 – radimpe 2013-04-04 12:57:59

0

您可以使用EntrySet的迭代器,或將所有重複鍵保存在另一個列表中,並稍後將其從地圖中刪除。另外,不要使用==比較對象,請使用equals()函數。