Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wrapper Pool

 
Sac Anand
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In K&B 5.0 (Page 234), it is written that

In order to save memory, two instances of the
following wrapper objects will always be == when their primitive values are the same:
- Boolean
- Byte
- Character from \u0000 to \u007f (7f is 127 in decimal)
- Short and Integer from -128 to 127

My understanding is that the implementation for the above is same as the String pool is maintained. Please validate.

My doubt is that apart from the above mentioned Wrapper Classes, Long also works in the same way but it is not covered in the above statement from K&B.
 
Petrus Pelser
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It does not work in the same way as the String pool, but sort of:

new Long(7) == 7, is true
String str = "7";
str == "7", is true but
new String(7) == "7", is false
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does the autoboxing conversion sometimes return the same reference?

Also, The Java Language Specification does not explicitly guarantee this behavior for long values within the range of a byte.
 
Sac Anand
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Petrus and Wise.
Got your point.
 
Aniket Patil
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to JLS, Long is not guaranteed to behave the same way, as the rule above.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic