Changing HashMap keys during iteration(在迭代期间更改 HashMap 键)
问题描述
是否可以在迭代期间更改同一 HashMap 实例的键?因为地图条目集没有方法entry.setKey().现在我能想到的是创建另一个 HashMap...
is it possible to change keys of a the same HashMap instance during iteration ? Because map entry set don't have a method entry.setKey(). Now what I can think off is create another HashMap...
MultipartParsingResult parsingResult = parseRequest(request);
Map<String, String[]> mpParams = parsingResult.getMultipartParameters();
Map<String, String[]> mpParams2 = new HashMap<String, String[]>();
Iterator<Entry<String,String[]>> it = mpParams.entrySet().iterator();
while (it.hasNext()) {
Entry<String,String[]> entry = it.next();
String name = entry.getKey();
if (name.startsWith(portletNamespace)) {
mpParams2.put(name.substring(portletNamespace.length(), name.length()), entry.getValue());
}
else {
mpParams2.put(name, entry.getValue());
}
}
推荐答案
您应该将信息保留在其他集合中,以便在迭代后对其进行修改.您只能在迭代器期间使用 iterator.remove()
删除条目.HashMap
合约禁止在迭代期间对其进行变异.
You should keep information in other collection to modify it after iteration. You can only remove entry using iterator.remove()
during iterator. HashMap
contract forbids mutating it during iteration.
这篇关于在迭代期间更改 HashMap 键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在迭代期间更改 HashMap 键


基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01