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)
When you do this :
integ=2;
strng="Bye";
you have only changed the reference to an object not the object itself.
for Integer and String you cannot change the object as they are immutable
so if you want to change the values in your map then solutionis :
You need to put the values again, so that existing values are overwritten, before you get from map again.
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";
objMap.put("integer", integ);
objMap.put("string", strng);
//Check values again
System.out.println(objMap.get("integer"));
System.out.println(objMap.get("string"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With