整数包装器对象只在值127内共享相同的实例?

整数包装器对象只在值127内共享相同的实例?

在这里,它们是相同的实例:

Integer integer1 = 127;Integer integer2 = 127;System.out.println(integer1 == integer2);  // outputs "true"

但在这里,它们是不同的例子:

Integer integer1 = 128;Integer integer2 = 128;System.out.println(integer1 == integer2);  // outputs "false"

为什么包装器对象只在值127内共享同一个实例?


慕村9548890
浏览 333回答 3
3回答

白衣染霜花

java.lang.Integer的来源:public&nbsp;static&nbsp;Integer&nbsp;valueOf(int&nbsp;i)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;final&nbsp;int&nbsp;offset&nbsp;=&nbsp;128; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(i&nbsp;>=&nbsp;-128&nbsp;&&&nbsp;i&nbsp;<=&nbsp;127)&nbsp;{&nbsp;//&nbsp;must&nbsp;cache &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;IntegerCache.cache[i&nbsp;+&nbsp;offset]; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;new&nbsp;Integer(i); &nbsp;&nbsp;&nbsp;&nbsp;}干杯!

胡子哥哥

顺便说一句,你可以把你的代码缩短到System.out.println("Integer&nbsp;127&nbsp;==&nbsp;"&nbsp;+&nbsp;((Integer)&nbsp;127&nbsp;==&nbsp;(Integer)&nbsp;127));System.out.println("Integer&nbsp;128&nbsp;==&nbsp;"&nbsp;+&nbsp;((Integer)&nbsp;128&nbsp;==&nbsp;(Integer)&nbsp;128));for(int&nbsp;i=0;i<5;i++)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;System.out.println( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"Integer&nbsp;127&nbsp;system&nbsp;hash&nbsp;code&nbsp;"&nbsp;+&nbsp;System.identityHashCode((Integer)&nbsp;127) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+&nbsp;",&nbsp;Integer&nbsp;128&nbsp;system&nbsp;hash&nbsp;code&nbsp;"+System.identityHashCode((Integer)&nbsp;128));}版画Integer&nbsp;127&nbsp;==&nbsp;trueInteger&nbsp;128&nbsp;==&nbsp;falseInteger&nbsp;127&nbsp;system&nbsp;hash&nbsp;code&nbsp;1787303145,&nbsp;Integer&nbsp;128&nbsp;system&nbsp;hash&nbsp;code&nbsp;202703779Integer&nbsp;127&nbsp;system&nbsp;hash&nbsp;code&nbsp;1787303145,&nbsp;Integer&nbsp;128&nbsp;system&nbsp;hash&nbsp;code&nbsp;1584673689Integer&nbsp;127&nbsp;system&nbsp;hash&nbsp;code&nbsp;1787303145,&nbsp;Integer&nbsp;128&nbsp;system&nbsp;hash&nbsp;code&nbsp;518500929Integer&nbsp;127&nbsp;system&nbsp;hash&nbsp;code&nbsp;1787303145,&nbsp;Integer&nbsp;128&nbsp;system&nbsp;hash&nbsp;code&nbsp;753416466Integer&nbsp;127&nbsp;system&nbsp;hash&nbsp;code&nbsp;1787303145,&nbsp;Integer&nbsp;128&nbsp;system&nbsp;hash&nbsp;code&nbsp;1106961350您可以看到,127每次都是相同的对象,而128的对象则不同。

温温酱

因为它是由Java语言规范指定的。JLS 5.1.7拳击转换:如果值p被装箱true,&nbsp;false..byte,或char在范围内\u0000到\u007f,或int或short编号在-128和127之间(包括在内),然后让r1和r2的任何两个装箱转换的结果。p..总是这样r1 == r2.理想情况下,对给定的原语值进行装箱。p,总能得到相同的引用。在实践中,使用现有的实现技术,这可能是不可行的。上述规则是一种务实的妥协。上面的最后一个子句要求某些公共值总是被装箱到不可区分的对象中。实现可能缓存这些,懒惰或急切。对于其他值,此公式不允许程序员对装箱值的标识进行任何假设。这将允许(但不需要)共享部分或所有这些引用。这确保了在大多数常见情况下,行为将是理想的行为,而不会造成不适当的性能损失,特别是在小型设备上。例如,内存有限的实现可能会缓存所有char和short价值,以及int和long值在-32K到+32K之间。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java