遍历entrySet时候怎么添加元素
时间: 2023-11-22 15:56:34 浏览: 39
在使用entrySet遍历Map时,不能直接添加元素,因为entrySet是Map的视图,任何对Map的修改都会反映到entrySet上。如果想要在遍历过程中添加元素,可以使用Iterator的add方法来实现。具体步骤如下:
1. 通过Map的entrySet方法获取Map的entrySet视图,并使用Iterator遍历该视图。
2. 在遍历过程中,使用Iterator的add方法添加新元素。注意,添加元素时需要使用Map.Entry对象作为参数,即新元素的键值对。
下面是一个示例代码,演示了如何在遍历Map的entrySet时添加新元素:
```
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println(entry.getKey() + ": " + entry.getValue());
if (entry.getValue() % 2 == 0) { // 如果值为偶数,则添加新元素
iterator.add(new AbstractMap.SimpleEntry<>("d", 4));
}
}
```
在上面的示例中,如果Map中存在值为2的键值对,则会在遍历到该键值对时添加一个新元素("d", 4)。需要注意的是,添加元素的操作必须使用Iterator的add方法,而不能直接通过Map的put方法添加,否则会导致ConcurrentModificationException异常。