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

我们首先看下面一段代码

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。

猜你喜欢

转载自www.cnblogs.com/NullCXY/p/9746495.html