简体   繁体   English

java将HashMap元素放入foreach循环内仅使用最后一个

[英]java put HashMap elements inside foreach loop use only the last one

I have a strength problem about adding elements into an HashMap inside a loop. 我有一个关于在循环内将元素添加到HashMap的强度问题。 I make sure to declare map before iteration, to ignore it's recreation each time but I got the same problem - in map remains only the last element from my loop iteration. 我确保在迭代之前声明map,每次都忽略它的重新创建,但是我遇到了同样的问题-map只是循环迭代中的最后一个元素。 The code is 该代码是

//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);
}

as a result, for simplicity calling map.toString() , I get only {uniqueKey=element3} 结果,为简单起见,调用map.toString() ,我只得到{uniqueKey=element3}

I just don't understand why this happens, any explanations will be appreciated. 我只是不明白为什么会这样,请多加解释。

Well you're trying to ignore the general concept of Map s about unique keys. 好吧,您正在尝试忽略Map关于唯一键的一般概念。 Make your "uniqueKey" "really" unique as you repeat it in the loop :) 当您在循环中重复它时,使您的"uniqueKey" “真正”唯一:

I'll give you an example to understand: 我举一个例子来理解:

 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

Think of Map s as List s, but with indices other than primitive int s and without the need to have the indices in range 0 .. size-1 Map视为List ,但具有除原始int以外的索引,并且无需使索引的范围为0 .. size-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM