Today is my first time to try Java language. When I try this code, I feel very strange:
int a =500;
System.out.println(System.identityHashCode(500));
System.out.println(System.identityHashCode(500));
System.out.println(System.identityHashCode(a));
System.out.println(System.identityHashCode(a));
All of these results is different. But when I changed 500 to 50, It become the same result.
Why is it?
As already mentioned int is a primitive data type and takes 32 bits(4 bytes) to store. On other hand Integer is an object which takes 128 bits (16 bytes) to store its int value.
Integers are whole numbers which will be stored in computer using 4 bytes (32 bit) of memory.
To find the memory address of a particular object in the JVM, we can use the addressOf() method: String answer = "42"; System.out.println("The memory address is " + VM.current().addressOf(answer)); This will print: The memory address is 31864981224. There are different compressed reference modes in the HotSpot JVM.
There is no way to get the memory address of anything in Java. All that is hidden by the JVM, you never have to worry about it. Even if you could get it, you couldn't do anything with it... Instead, you identify objects by other means, typically by implementing their equals() and hashCode() methods.
But when I changed 500 to 50, It become the same result.
Autoboxing caches the conversion of primitives to Object. Small values get the same object, larger values do not.
Note: while values between -128 and 127 are always cached, Higher values can be cached depending on command line settings. See the source for Integer
for more details.
This is also called a Flyweight Pattern
You can set the maximum size of the Integer cache with
-Djava.lang.Integer.IntegerCache.high=NNNN
-XX:AutoBoxCacheMax=NNNN
-XX:+AggressiveOpts // sets it higher depending on the version e.g. 10000
http://martykopka.blogspot.co.uk/2010/07/all-about-java-integer-cache.html
http://www.javaspecialists.eu/archive/Issue191.html
I feel very strange
I know what you mean reading this question. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With