aspose file tools*
The moose likes Beginning Java and the fly likes HashMap put() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "HashMap put()" Watch "HashMap put()" New topic
Author

HashMap put()

Allen Bandela
Ranch Hand

Joined: Feb 16, 2006
Posts: 128

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.


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: 18990
    
  40

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)
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: HashMap put()