Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashMap put()

 
Allen Bandela
Ranch Hand
Posts: 128
Eclipse IDE MS IE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21117
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic