码迷,mamicode.com
首页 > 编程语言 > 详细

为什么Java中1000==1000为false而100==100为true

时间:2018-10-06 10:44:41      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:ecif   -128   enc   sys   结果   required   方法   values   rally   

我们首先看下面一段代码

Integer a = 1000,b=1000;
System.out.println(a==b);
Integer c = 100,d = 100;
System.out.println(c==d);

运行结果如下

技术分享图片

 

按照我们的理解,如果两个引用指向同一个对象,用==表示它们是相等的。如果两个引用指向不同的对象,==代表不相等的,即使它们的内容相同。

因此,后面一条语句应该也是false。

分析:

我们看下Integer.java类,我们会发现有一个内部私有类,IntegerCache.java,它缓存了从-128~127之间的所有的整数对象。

所以我们在声明类似——

Integer c = 100;

的时候,它实际上在内部做的是——

Integer i = Integer.valueOf(100);

 

我们看下valueOf()方法,可以看到

 1     /**
 2      * Returns an {@code Integer} instance representing the specified
 3      * {@code int} value.  If a new {@code Integer} instance is not
 4      * required, this method should generally be used in preference to
 5      * the constructor {@link #Integer(int)}, as this method is likely
 6      * to yield significantly better space and time performance by
 7      * caching frequently requested values.
 8      *
 9      * This method will always cache values in the range -128 to 127,
10      * inclusive, and may cache other values outside of this range.
11      *
12      * @param  i an {@code int} value.
13      * @return an {@code Integer} instance representing {@code i}.
14      * @since  1.5
15      */
16     public static Integer valueOf(int i) {
17         if (i >= IntegerCache.low && i <= IntegerCache.high)
18             return IntegerCache.cache[i + (-IntegerCache.low)];
19         return new Integer(i);
20     }

如果值的范围在-128~127之间,它就从高速缓存返回实例。

所以——

Integer c = 100,d = 100;

指向同一个对象,所以输出才会是true。

 

为什么Java中1000==1000为false而100==100为true

标签:ecif   -128   enc   sys   结果   required   方法   values   rally   

原文地址:https://www.cnblogs.com/NullCXY/p/9746495.html

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