List<e> Object Assignment operation problem in Java
The business requirement is to take the intersection object from 2 sets and return. In the following code, the key value in Busmap and the key value in the map in stocks return to the continuation operation, that is, to exclude objects in the stocks that do not exist in Busmap, is a filtering operation.
Implementing Code ① Bug Edition
Error:
Java.util.ConcurrentModificationException; At Java.util.arraylist$itr.checkforcomodification (arraylist.java:859); At Java.util.arraylist$itr.next (arraylist.java:831);
Reason:
The foreach implementation is implemented using iterator, and the remove operation cannot operate under iterator, so the error
private static void appendStock(Map<String,Object> busMap, List<Map<String, Object>> stocks , String key){ if (stocks != null) for (Map<String,Object> s : stocks ) { boolean b = false; for (Map.Entry<String, Object> e : busMap.entrySet()) { if (s.get("stock_code") != null) if (s.get("stock_code").toString().equals(e.getKey())) { b = true; break; } } if ( !b ){ stocks.remove(s); } }}
code ② fix for Remove exception in foreach, bug version
Bug
After executing this method, stocks has not changed!!
Reason:
Object Shallow copy Causes
private static void appendStock(Map<String,Object> busMap, List<Map<String, Object>> stocks , String key){ if (stocks != null) List<Map<String,Object>> newStocks = Lists.newArrayList(); // 构建新对象保存交集数据 for (Map<String,Object> s : stocks ) { for (Map.Entry<String, Object> e : busMap.entrySet()) { if (s.get("stock_code") != null) if (s.get("stock_code").toString().equals(e.getKey())) { newstocks.add(s); break; } } } stocks = newStocks;}
Code ③ Bypass Shallow copy, stable version
Use iterator to remove elements, discard copies, and thus not into shallow copy pits
private static void appendStock(Map<String,Object> busMap, List<Map<String, Object>> stocks , String key){ if (stocks != null && stocks.size() > 0) { Iterator<Map<String, Object>> iterator = stocks.iterator(); while (iterator.hasNext()) { Map<String, Object> s = iterator.next(); if (s.get("stock_code") != null) { String stockCode = String.valueOf(s.get("stock_code")); if ( !busMap.containsKey(stockCode)) { iterator.remove(); } } } }}
code ④ fix Shallow copy, stable version
List<e> object Assignment problem in Java (deep copy)