【发布时间】:2015-10-01 11:19:50
【问题描述】:
在使用 Object 作为类型时,我很难理解 HashMap。
在这里,我创建了两个对象,一个字符串和一个整数,并为其赋值。然后我将这些对象添加到 HashMap。然后更改字符串和整数对象的值。但是当尝试使用HashMap.get() 引用它们时,它会显示原始值。
我假设在将值放在 HashMap 上时,会以某种方式在 HashMap 实例中创建一个新的未更改对象,而不是链接底层的原始对象?
代码如下:
import java.util.HashMap;
import java.util.Map;
public class Test1 {
//Create objects
static int integ=1;
static String strng="Hi";
//Create HashMap
static Map<String, Object> objMap = new HashMap(); //Map of shipments
public static void main(String[] args) {
//Insert objects in HashMap
objMap.put("integer", integ);
objMap.put("string", strng);
//Check the values
System.out.println(objMap.get("integer"));
System.out.println(objMap.get("string"));
//Change values of underlying object
integ=2;
strng="Bye";
//Check values again
System.out.println(objMap.get("integer"));
System.out.println(objMap.get("string"));
}
}
还有输出:
debug:
1
Hi
BUILD SUCCESSFUL (total time: 8 seconds)
【问题讨论】:
标签: java dictionary hashmap