| Author |
HashMap put()
|
Allen Bandela
Ranch Hand
Joined: Feb 16, 2006
Posts: 127
|
|
Hello:
I've stumbled across an unexpected behaviour (atleast for me) on using the HashMap.put(Object, Object) method.
Would you expect the value assigned to key 'o' to be 3? I did. But, its 2. passing values to method in Java is pass by value, correct? in other words isn't the JVM passing the address in 'i' to put(..) above?
Well, basically, I was going through past code and found this. I thought, hey , there's a bug, 'i' was already incremented . But, it was working as intended.
Thanks.
|
Life is like a day. If the day is of no use, neither a month or a year.
|
 |
John de Michele
Rancher
Joined: Mar 09, 2009
Posts: 600
|
|
Allen,
On your line 6, you have
What this says is "Associate the value of 'i' with the key 'o' in HashMap 'c', then increment 'i'". If you want i to be 3, you need do this:
John.
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16680
|
|
Would you expect the value assigned to key 'o' to be 3? I did. But, its 2. passing values to method in Java is pass by value, correct? in other words isn't the JVM passing the address in 'i' to put(..) above?
Integer objects are immutable -- so i++ is really unboxing, incrementing, and reboxing (yielding a different object).
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
 |
|
|
subject: HashMap put()
|
|
|