This week's book giveaway is in the Cloud/Virtualizaton forum.
We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!
See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

maximum Integer value problem with HashMap(String, Integer)?

 
paul reberg
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi. I have



I've noticed that if the value for myKey is over 127 (2^7-1), then I get the error message. Otherwise, if it's 127 or less, I'll get the success message. Why does this happen? And, what would you do in situations where the value is more than 128 (2^7)?

Thanks!

 
Pat Farrell
Rancher
Posts: 4678
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am surprised that any of your tests get success. You need to use the "equals()" function, not ==
 
paul reberg
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ah, brain fart. yeah, you're right. i want to compare the values, not whether they're referring to the same object. however, the part that still confuses me is that they're clearly both different, distinct objects, which SHOULD mean != will always return true. But, if you test out the code, != will return either true or false depending on what you store as the value. Seems pretty odd, right?
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Constant pooling for values < 128.

(Wouter's answer is better-I just hate typing on the iPad :)
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It returns false because you use autoboxing to create your Integer objects.
Autoboxing uses the method Integer.valueOf(int) to create Integer objects.
That method use a cache and because of that, and the fact that Integer object are immutable, you get the same objects. So != returns false.

The range of that cache is -128 to 127 or the value set with java.lang.Integer.IntegerCache.high property with a minimum of 127.
 
paul reberg
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ahhh, i c. Ok, thanks alot for the insight!
 
Rob Spoor
Sheriff
Pie
Posts: 20529
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
paul reberg wrote:ahhh, i c. Ok, thanks alot for the insight!

Sorry to be nitpicking, but it's "I see", not "i c". Please UseRealWords.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic