我在将元素添加到循环内的 HashMap
时遇到强度问题。我确保在迭代之前声明映射,以忽略每次的重新创建,但我遇到了同样的问题 - 映射中仅保留循环迭代中的最后一个元素。代码是
//declare map
Map<String, String> map = new HashMap<String, String>();
//my loop iteration
String[] array = {"element1", "element2", "element3"};
for (String str: array) {
map.put("uniqueKey", str);
}
因此,为了简单起见,调用 map.toString()
,我只得到 {uniqueKey=element3}
我只是不明白为什么会发生这种情况,任何解释将不胜感激。
最佳答案
好吧,您试图忽略 Map
关于唯一键的一般概念。当您在循环中重复它时,使您的“uniqueKey”
“真正”唯一:)
我给你举个例子来理解:
Map<String, String> map = new HashMap<>();
map.put("1", str1);
map.put("2", str2);
map.put("3", str3);
map.put("1", str4); // value str1 is overwritten by str4
将 Map
视为 List
,但具有除原始 int
以外的索引,并且无需将索引置于范围内0
..size-1
关于java将HashMap元素放入foreach循环中仅使用最后一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34062551/