这个Integer比较真的是坑啊..........
先看代码,大家来猜猜,看看到底会输出什么:
1 public class Test1 {
2
3 public static void main(String[] args) {
4 Integer a = 128;
5 Integer b = 128;
6 int c = 128;
7 System.out.println(a==b);//false
8 System.out.println(b==c);//true
9 System.out.println(c==b);//true
10
11 System.out.println("=========");
12 Integer a1 = 10;
13 Integer b1 = 10;
14 int c1 = 10;
15 System.out.println(a1==b1);
16 System.out.println(b1==c1);
17 System.out.println(c1==b1);
18 System.out.println("=========");
19
20 int a11 = 10;
21 Integer b11 = new Integer(10);
22 System.out.println(a11== b11); //Line 1
23
24 Integer a2 = 127;
25 Integer b2 = 127;
26 System.out.println(a2==b2); //Line 2
27
28 Integer a3 = 128;
29 Integer b3 = 128;
30 System.out.println(a3 == b3); //Line 3
31
32 Integer a4 = new Integer(10);
33 Integer b4 = new Integer(10);
34 System.out.println(a4==b4); //Line 4
35
36 }
37
38 }
结果如下:
false true true ========= true true true ========= true true false false
不知猜对几道???笑哭...
先说下我的错误思路!!!
之前我是认为:Integer的话,不论范围多少,都是一个new 了一个对象,然后,不同的对象肯定地址也不相同,当==的时候,总是false;
而由int-->integer自动装箱时,如果是像第8行那样,也是两个不同对象,但像第9行那样,就成了拆箱成int ,比较的就是数值大小。
现在发现,这完完全全就是错误的!!!!!!!
哭晕到厕所.....
等会儿,容我先解释解释再去/...
查了些资料,直接看源码吧,看看==这个操作到底是怎么实现的。
/* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*/
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);//如果不在区间内,则新返回一个new对象;
}
看到了没!!!
这里low是-128,high是127,从方法的注释中可以得知:
在[-128,127]之间,Integer总是缓存了相应数值对象,这样每次取值时都是同一个对象;
而不在此区间时,则不一定会缓存,那么取出两个同样数值大小的对象则不是同一个对象,每次都会new Integer(i);
所以其对象的地址不同,则用==比较是自然不会成立。
另外需要注意的是,若是直接new Integer(n),则不管n是否在[-128, 127]范围内,都是不同的对象,而当没有显示new 出对象时,则利用缓存里的对象,此时是同一个对象(都是缓存内的那个)。
Over....
参考: