'java reference variable not working as expected when used with unary increment(decrement) operations
In the code bellow I excpected the Output to be true, 0. However the output is true, 1. Since cnt is a reference variable to the Value of the Key-Value Pair with Key 3. I thought the operation cnt--; would change the value where the reference variable is pointing at. However the experimental code shown bellow doesn't seem to change the value in the HashMap.
I'm confused because if get method returns a copy of the instance, then the equals operation should return false. Yet it is returning true so it is just returning a reference to an instance. Then why is that unary decrement operation not working?
Thank you in advance. Any feedback to the clarity of the question is welcome.
import java.util.HashMap;
import java.util.Map;
public class Equals {
public static void main(String[] args) {
int[] nums1 = new int[] { 1, 2, 3, 4, 5 };
Map<Integer, Integer> map = new HashMap<>();
for (int n : nums1) {
map.put(n, map.getOrDefault(n, 0) + 1);
}
Integer cnt = map.getOrDefault(3, 0);
Integer cnt2 = map.get(3);
System.out.println(cnt.equals(cnt2));
cnt--;
System.out.println(cnt2);
}
}
Solution 1:[1]
The -- operation is an operation on a variable. In the case of an Integer variable, it updates the variable to a new reference value ... representing the number - 1. It is equivalent to
// cnt--;
cnt = Integer.valueOf(cnt.intValue() - 1);
The -- operator cannot change the value held within the existing Integer object. Integer objects are immutable!
So ... when you increment the variable, it doesn't affect the value in the HashMap entry.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stephen C |
