Java Mapの全要素を削除する
正しい例
Map<String, Object> aMap = new HashMap<>(); aMap.put("key1", null); aMap.put("key2", null); aMap.put("key3", null); // キーのイテレータを取得 Iterator<String> mapKeyIter = aMap.keySet().iterator(); while(mapKeyIter.hasNext()) { String key = mapKeyIter.next(); if(key.equals(key)) { mapKeyIter.remove(); } }
以下がポイント
- イテレータを使用
- keyが等しいか比較
イテレータのメソッド
メソッド | 説明 |
---|---|
Iterator#hasnext() | 次の要素があればTrueを返す |
Iterator#next() | 次のデータを返す |
Iterator#remove() | 直前に読み込んだ要素を削除 |
悪い例
Map<String, Object> aMap = new HashMap<>(); aMap.put("key1", null); aMap.put("key2", null); aMap.put("key3", null); // ここで全部の要素削除! for(Map.Entry<String, Object> entry: aMap.entrySet()) { aMap.remove(entry.getKey()); }
上記のプログラムではjava.util.ConcurrentModificationExceptionが出てしまう
参考文献
MSC06-J. 繰り返し処理中に基となるコレクションを変更しない