I am having difficulties understanding the HashMap when using Object as a type.
Here I create two objects, a string and an integer, which I assign a value to. I then add these object to a HashMap. Then the values of the string and integer objects are changed. But when trying to refer to them using the HashMap.get()
it shows the original values.
I assume that somehow when putting the values on the HashMap create a new unchanged object is created in the HashMap instance instead of linking the underlying original object?
Here is the code:
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"));
}
}
And the output:
debug:
1
Hi
BUILD SUCCESSFUL (total time: 8 seconds)