我们首先看下面一段代码
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 {@codeInteger} instance representing the specified3 * {@codeint} value. If a new {@codeInteger} instance is not4 * required, this method should generally be used in preference to5 * the constructor {@link#Integer(int)}, as this method is likely6 * to yield significantly better space and time performance by7 * 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 *@parami an {@codeint} value.13 *@returnan {@codeInteger} instance representing {@codei}.14 *@since1.515 */
16 public static Integer valueOf(inti) {17 if (i >= IntegerCache.low && i <=IntegerCache.high)18 return IntegerCache.cache[i + (-IntegerCache.low)];19 return newInteger(i);20 }
如果值的范围在-128~127之间,它就从高速缓存返回实例。
所以——
Integer c = 100,d = 100;
指向同一个对象,所以输出才会是true。
原文:https://www.cnblogs.com/NullCXY/p/9746495.html