I have a HashMap:
private HashMap<String, Integer> cardNumberAndCode_ = new HashMap<String, Integer>();
And later I do this:
Integer balance = cardNumberBalance_.get(cardNumber);
System.out.println(balance);
balance = 10;
Integer newBalance = cardNumberBalance_.get(cardNumber);
System.out.println(newBalance);
First it prints 1000, and the second time it’s printing 1000, the value does not change. Why is Java returning the Integer by value and not by reference?
The
getmethod returns a copy of the reference to the stored integer…Assigning a new value to the variable storing this copy in order to point to the value
10will not change the reference in the map.It would work if you could do
balance.setValue(10), but sinceIntegeris an immutable class, this is not an option.If you want the changes to take affect in the map, you’ll have to wrap the balance in a (mutable) class:
But you would probably want to do something like this instead: