This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 18552
    
  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)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: HashMap put()
 
Similar Threads
Please Help: Putting Vector objects into HashMap
JTable inside JScrollPane - background coloring problem
How can i browse 3 files (same file format, exp: .txt) and process it ?
LinkedHashMap - trying to use the method removeEldestEntry
HashMap dilemma