当前位置: 首页 > 后端技术 > Java

经典面试题:整数c=100,d=100,c==d一定为假?

时间:2023-04-02 01:23:45 Java

相信大家在面试的过程中可能都遇到过这样的问题吧!publicstaticvoidmain(String[]args){整数a=1000,b=1000;整数c=100,d=100;System.out.println(a==b);System.out.println(c==d);}相信大家的答案都是falsetrue,但是在这里我必须说这个答案不是绝对的,c==d一定是true,但是a==b不一定是false,也有可能是true。但是我得到的数值是真实的,真实的,如果你不相信或者有疑问,请继续往下看!我们首先需要了解为什么答案通常是假的,真。Integerc=1000实际上在内部执行Integerc=Integer.valueOf(100)的操作。我们来看看Integer.class的源码。/***返回表示指定*{@codeint}值的{@codeInteger}实例。如果一个新的{@codeInteger}实例不是*必需的,这个方法通常应该优先于*构造函数{@link#Integer(int)}使用,因为这个方法很可能*产生更好的空间和时间性能通过*缓存经常请求的值。**此方法将始终缓存-128到127范围内的值,*包括在内,并可能缓存此范围之外的其他值。**@parami一个{@codeint}值。*@return一个代表{@codei}的{@codeInteger}实例。*@since1.5*/publicstaticIntegervalueOf(inti){if(i>=IntegerCache.low&&i<=IntegerCache.high)returnIntegerCache.cache[i+(-IntegerCache.low)];返回新整数(i);}从上面的代码中可以看到,当i>=IntegerCache.low&&i<=IntegerCache.high的时候会从cache数组里直连值,否则新建一个新的Integer对象privatestaticclassIntegerCache{staticfinalintlow=-128;静态最终int高;静态最终整数缓存[];static{//高值可以由属性配置inth=127;StringintegerCacheHighPropValue=sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");if(integerCacheHighPropValue!=null){try{inti=parseInt(integerCacheHighPropValue);i=Math.max(i,127);//最大数组大小为Integer.MAX_VALUEh=Math.min(i,Integer.MAX_VALUE-(-low)-1);}catch(NumberFormatExceptionnfe){//如果属性无法解析为int,则忽略它。}}高=h;cache=newInteger[(high-low)+1];intj=低;对于(整数k=0;k<缓存长度;k++)缓存[k]=新整数(j++);//范围[-128,127]必须被保留(JLS75.1.7)assertIntegerCache.high>=127;}privateIntegerCache(){}}从上面Integer.class的源码可以看出,low的默认值为-128,high的值与integerCacheHighPropValue有关,StringintegerCacheHighPropValue=sun.misc.VM。getSavedProperty("java.lang.Integer.IntegerCache.high");当我们在vm中还没有设置Integercache的时候,其实是127,缓存数组从-128到127。不难理解为什么开篇提到的经典面试题目的结果会是false和真实的。后面会强调的原因是ntegerCacheHighPropValue不为null时,取决于jvm中的设置。在eclipse中,我们可以这样做:此时再次执行那段代码,你会得到结果是真的,下次谁问你这样的问题,你可以大声告诉他,这不一定是真的,假装13岁!来源:https://sourl.cn/PsR8Kv

最新推荐
猜你喜欢