0

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());
four
  • 65
  • 5
  • Because Java is pass by value where value in case of non-primitives is object reference. Check https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – Smile Jan 09 '20 at 06:45

4 Answers4

3

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

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
talex
  • 17,973
  • 3
  • 29
  • 66
0

it is the same case as the following

    Student student = map.get(1);
    student = new Student(5,"something")  // map value is NOT updated
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
0

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.

Smile
  • 3,832
  • 3
  • 25
  • 39
0

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.

Reyem
  • 31
  • 6