• Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparing objects  RSS feed

 
Aleksey Movchan
Ranch Hand
Posts: 49
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

prints:

false
true


Why?
 
Pete Letkeman
Ranch Foreman
Posts: 914
26
Android Chrome IntelliJ IDE Java MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is an cache for wrapper objects which are in the -128 to 127 range.
Here the objects are not cached

Here, i4 is a cached object from i3

Here is an article (may not be the best) explaining this
https://howtodoinjava.com/core-java/basics/object-initialization-best-practices-internal-caching-in-wrapper-classes/
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are a few minor errors in that link, but it has the good point that it shows how to cache a larger range than −128…127. The definitive descriptions are in the Integer class and the Java® Language Specification. It explains how the valueOf method is better than the constructor, so the constructor will be deprecated in the not too distance future.
 
Aleksey Movchan
Ranch Hand
Posts: 49
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you!
 
Aleksey Movchan
Ranch Hand
Posts: 49
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pete Letkeman wrote:



Shouldn't it be then:

 
Pete Letkeman
Ranch Foreman
Posts: 914
26
Android Chrome IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, first time initialized with i3 the object needs to be created and put into cache.
So this is what happens
 
Luke Lu
Greenhorn
Posts: 7
1
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That because Integer class cached Integer object range from -128 to 127 when your program loaded.To be exact,is the Integer class `s inner class IntegerCache implements the magic/



Beacuse small int value is frequently used in our porgram , and Integer is designed to be inmutable object , so cache is  for performance reason.If we new Integer object vlaue between -128 and 127,JVM need not to allocate memory and init it.just create a reference and pointer to cached Integer object.It is fast.
However , we can`t cached all int value , so if new Integer object value out of the cachaed range, JVM should allocate memory in head and init it every time.
so code below let JVM create two Integer in heap Respectivly,they have different address,so print false



but  cached Integer object are shared in program, that means i3 and i4 pointer to same memory object that has been cached ,so they equals,print true.





 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!