对于下面的代码,在打印出HashMap temp
的HashMap时,为什么会打印
{0={PRICE=2.2, NAME=2str}, 1={PRICE=2.2, NAME=2str}}
作为输出而不是获取 {0={PRICE=2, NAME=1str}, 1={PRICE=2.2, NAME=2str}}
?
请告知是否有不同的基本概念用于创建此类 HashMap ?
我试过在 test.put(0,temp);
之后插入 temp.clear();
但结果还是一样。
import java.util.*;
public class TestClass {
public static void main(String args[]){
HashMap<Integer,HashMap<String, Object>> test = new HashMap<Integer,HashMap<String, Object>>();
HashMap<String,Object> temp = new HashMap<String, Object>();
temp.put("NAME","1str");
temp.put("PRICE", 2);
test.put(0,temp);
System.out.println(temp);
temp.put("NAME","2str");
temp.put("PRICE",2.2);
test.put(1,temp);
System.out.println(temp);
System.out.println(test);
}
}
最佳答案
您正在使用 map 的相同实例,因此请考虑键发生了什么。
关于java - Java 1.8中HashMap的HashMap检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53611232/