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?
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
Integerfor more details.This is also called a Flyweight Pattern
You can set the maximum size of the Integer cache with
http://martykopka.blogspot.co.uk/2010/07/all-about-java-integer-cache.html
http://www.javaspecialists.eu/archive/Issue191.html
I know what you mean reading this question. 😉