Basic types Integer, Long noted that other packaging point of comparison

First look at a piece of code:
Integer a = 1;
Integer b = 1;
System.out.println(a == b);     // true
 
Integer aa = 128;
Integer bb = 128;
System.out.println(aa == bb);   // false
 
Why is this output? This way Integer created with objects related to the. In the process of creating an object using Integer, the first calls valueOf () method, the source code is as follows
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
Integer parameters have passed a judgment, <i <IntegerCache taken directly from the cache 127 when the -128, when outside this range, a new heap object.
Thus, a and b in the above code actually point to the same address in IntegerCache, and aa and bb exceeds this range -128 to 127, they point to a different object heap.
 
Long.vlaueOf () Source
public static Long valueOf(long l) {
    final int offset = 128;
    if (l >= -128 && l <= 127) { // will cache
        return LongCache.cache[(int)l + offset];
    }
    return new Long(l);
}
You can see, Long same is true
 
So, when we compare these wrapper classes, it should be compared using equals, so that we can avoid these accidents from happening.
Integer aa = 128;
Integer bb = 128;
System.out.println(aa.equals(bb));   // true
 

Guess you like

Origin www.cnblogs.com/sxhjoker/p/11647345.html