码迷,mamicode.com
首页 > 其他好文 > 详细

发现个有趣的

时间:2017-05-23 14:57:54      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:div   val   ati   class   integer   就会   缓存   -128   编译   

1 Integer i5 = 127;//编译的时候,被翻译成-> Integer i5 = Integer.valueOf(127);
2 Integer i6 = 127;
3 System.out.println(i5 == i6);
4 
5 Integer i5 = 128;
6 Integer i6 = 128;
7 System.out.println(i5 == i6);

第一个输出true,而第二个是false.神奇吧。

下面来看看源码

public static Integer valueOf(int i) {
         assert IntegerCache.high >= 127;
         if (i >= IntegerCache.low && i <= IntegerCache.high)
             return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
}

对于-128到127之间的数,会对其进行缓存,Integer i5 = 127时,会将127进行缓存,下次再申明Integer i6 = 127时,
就会直接从缓存中取,而不会new了。所以结果为true,而第二个则为false。

发现个有趣的

标签:div   val   ati   class   integer   就会   缓存   -128   编译   

原文地址:http://www.cnblogs.com/lengbumo/p/6894041.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!