Here's a piece of code:
public
class
Main {
public
static
void
main(String[] args) {
Integer i1 =
100
;
Integer i2 =
100
;
Integer i3 =
200
;
Integer i4 =
200
;
System.out.println(i1==i2);
System.out.println(i3==i4);
}
}
Its output is this: true false; The reason is simple:
The output shows that I1 and I2 point to the same object, while i3 and I4 point to different objects. At this point only a look at the source code will know, the following is an integer valueof method of the specific implementation:
public static Integer valueOf (int i) { if (i >= -128 && i <= integercache.high) return integercache.c Ache[i + +]; else return new Integer (i); }
public static Integer valueOf (int i) { if (i >= -128 && i <= integercache.high) return Integercache . cache[i + +]; else return new Integer (i); }
Where the Integercache class is implemented as:
private static class Integercache { static final int high; Static final Integer cache[]; static { final int low = -128; High value is configured by property int h = 127; if (integercachehighpropvalue! = null) { //use Long.decode. Avoid invoking methods that //require Integer ' s autoboxing cache to be initialized int i = Long.decode (integercachehighpropvalue). Intvalue (); i = Math.max (i, 127); Maximum array size is integer.max_value h = math.min (i, Integer.max_value--low); } High = h; cache = new Integer[(high-low) + 1]; int j = Low; for (int k = 0; k < cache.length; k++) cache[k] = new Integer (j + +); } Private Integercache () {} }
private static class Integercache { static final int high; Static final Integer cache[]; static { final int low = -128; High value is configured by property int h = 127; if (integercachehighpropvalue! = null) { //use Long.decode. Avoid invoking methods that //require Integer ' s autoboxing cache to be initialized int i = Long.decode (integercachehighpropvalue). Intvalue (); i = Math.max (i, 127); Maximum array size is integer.max_value h = math.min (i, Integer.max_value--low); } High = h; cache = new Integer[(high-low) + 1]; int j = Low; for (int k = 0; k < cache.length; k++) cache[k] = new Integer (j + +); } Private Integercache () {} }
As you can see from these 2 pieces of code, when you create an integer object by using the ValueOf method, if the value is between [-128,127], a reference to the object that already exists in Integercache.cache is returned, otherwise a new integer object is created.
The values for I1 and I2 in the above code are 100, so the objects that already exist are taken directly from the cache, so i1 and I2 point to the same object, while i3 and I4 point to different objects respectively.
Two pairs of integers are exactly the same, why is one output true and one output false?