four
four

Reputation: 65

Update value object in Map in Java

I have a HashMap defined in java as below: I want to understand why the value is not updated in map in 1st scenario?

SCENARIO 1:

HashMap<Character, Integer> charCountMap 
            = new HashMap<Character, Integer>(); 
char[] strArray = inputString.toCharArray(); 
for (char c : strArray) { 
            if (charCountMap.containsKey(c)) { 

                // If char is present in charCountMap, 
                // incrementing it's count by 1 
                Integer i = charCountMap.get(c);
                i = i + 1;                             //This statement doesn't update the value in map 
                //charCountMap.put(c, charCountMap.get(c) + 1); 
            } 
            else { 

                // If char is not present in charCountMap, 
                // putting this char to charCountMap with 1 as it's value 
                charCountMap.put(c, 1); 
            } 
        }

SCENARIO 2:

HashMap<Integer, Student> map = new HashMap<Integer, Student>();
        map.put(1, new Student(1,"vikas"));
        map.put(2, new Student(2,"vivek"));
        map.put(3, new Student(3,"ashish"));
        map.put(4, new Student(4,"vipin"));

        System.out.println(map.get(1).toString());
        Student student = map.get(1);
        student.setName("Aman");                //This statement updates the value in map.
        System.out.println(map.get(1).toString());

Upvotes: 0

Views: 339

Answers (4)

talex
talex

Reputation: 20455

Integer is immutable. i = i + 1 creates new object.

Upvotes: 3

Reyem
Reyem

Reputation: 46

Because the + operator does not modify objects. It creates a new one, meaning the object in your map is not changed. You need to call

charCountMap.put(c,i)

To replace the value for c with the result of your addition.

Upvotes: 0

Smile
Smile

Reputation: 4088

Java is pass by value where value in case of primitives is the value of primitive and in case of non-primitives is object reference. Check Java pass by reference or value for more detailed discussion on this.

Upvotes: 0

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

it is the same case as the following

    Student student = map.get(1);
    student = new Student(5,"something")  // map value is NOT updated

Upvotes: 0

Related Questions