This week's book giveaway is in the Testing forum.
We're giving away four copies of Data Structures the Fun Way: An Amusing Adventure with Coffee-Filled Examples and have Jeremy Kubica on-line!
See this thread for details.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

HashMap put()

 
Ranch Hand
Posts: 128
MS IE Eclipse IDE Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.


 
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author
Posts: 23928
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Don't touch me. And dont' touch this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic