Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing multiple type objects in HashMap and retrieving them

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)
like image 970
Ernesto Avatar asked May 19 '26 06:05

Ernesto


2 Answers

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 :

  1. remove the previous values from the map.
  2. change the values
  3. add them to your map
like image 86
nafas Avatar answered May 21 '26 21:05

nafas


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"));
    }
like image 36
Rahul Yadav Avatar answered May 21 '26 21:05

Rahul Yadav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!