Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Autoboxing & Generics Caveat

 
Ustad Hanif
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could someone kindly tell me why the following piece of code behaves the way it does? Basically I've defined a hashmap where the key is a Long object. I populate the map with an entry and then try and retrieve that entry with an int primitive. I understand the int I pass into get() is autoboxed into an Integer. The compile-time check asserts that myint can be promoted from int to long, but what is happening at run-time that causes a value of 'null' to be returned? I prostrate before the Ranch and beseech its apt members for guidance!!




results:
my value for int key is: null
my value for long key is: hello
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


That last line of code is what the Map's key matching will be doing (if the hashCodes even match in the first place, which they may or may not).
 
Ustad Hanif
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Concise, right to the point and beautifully answered! Thanks also for the lightning speed response time Jeff!
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're quite welcome. Glad I could help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic