我正在尝试将 2 个 HashMap 的数据打印到控制台,但我注意到那里只描绘了一个。这是一个代码示例:
public class HashMapsmathces {
public static void main(String[] args) throws Exception {
Map<String, Object> hm1 = new HashMap<>();
hm1.put("id", 1);
hm1.put("sku","qazwsx");
hm1.put("price", 11);
printMaps(hm1);
Map<String, Object> hm2 = new HashMap<>();
hm1.put("id", 2);
hm1.put("sku","qazwsx");
hm1.put("price", 13);
printMaps(hm2);
}
public static void printMaps(Map<String, Object> map)
{
for (Map.Entry<String, Object> pair : map.entrySet())
{
String key = pair.getKey();
String value = pair.getValue().toString();
System.out.println(key + " : " + value);
}
}
}
因此,当我按“运行”时,只有 hm1
会被推送到控制台。我不太清楚为什么。
这里还有截图 enter image description here
谢谢。
最佳答案
那是因为 hm2 为空,您在声明 hm2 映射后将值重新分配给 hm1。
public class HashMapsmathces {
public static void main(String[] args) throws Exception {
Map<String, Object> hm1 = new HashMap<>();
hm1.put("id", 1);
hm1.put("sku","qazwsx");
hm1.put("price", 11);
printMaps(hm1);
Map<String, Object> hm2 = new HashMap<>();
hm2.put("id", 2);
hm2.put("sku","qazwsx");
hm2.put("price", 13);
printMaps(hm2);
}
public static void printMaps(Map<String, Object> map)
{
//напишите тут ваш код
for (Map.Entry<String, Object> pair : map.entrySet())
{
String key = pair.getKey();
String value = pair.getValue().toString();
System.out.println(key + " : " + value);
}
}
}
关于java - Intellij idea Hashmaps打印到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42606664/