为什么相同的整数值在Java中具有不同的内存地址?

Leo*_*Shi 5 java memory

今天是我第一次尝试Java语言.当我尝试这段代码时,我觉得很奇怪:

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));
Run Code Online (Sandbox Code Playgroud)

所有这些结果都不同.但当我将500改为50时,它会变成相同的结果.

为什么?

Pet*_*rey 12

但当我将500改为50时,它会变成相同的结果.

Autoboxing缓存基元到Object的转换.小值获得相同的对象,较大的值不获得.

注意:虽然始终缓存介于-128和127之间的值,但可以根据命令行设置缓存较高的值.有关Integer更多详细信息,请参阅源代码.

这也称为Flyweight模式


您可以使用设置Integer缓存的最大大小

-Djava.lang.Integer.IntegerCache.high=NNNN
-XX:AutoBoxCacheMax=NNNN
-XX:+AggressiveOpts  // sets it higher depending on the version e.g. 10000
Run Code Online (Sandbox Code Playgroud)

http://martykopka.blogspot.co.uk/2010/07/all-about-java-integer-cache.html

http://www.javaspecialists.eu/archive/Issue191.html

我觉得很奇怪

我知道你读这个问题的意思.;)