If you run the following code:
1234 |
Integer a = 1000 , b = 1000 ; System.out.println(a == b); //1 Integer c = 100 , d = 100 ; System.out.println(c == d); //2 |
You will get the following running results:
We know that if two references point to the same object, then = = is set up, whereas if two references are not the same object, then = = is not true, even if the contents of the two references are the same. Therefore, the result will appear false.
This is a very interesting place. If you look at the Integer.java class, you will find Integercache.java this internal private class, which provides caching for all integer objects between 128 and 127.
This thing provides an internal cache for those numbers that are relatively small, and when this is declared:
The interior of it is this:
1 |
Integer i = Integer.valueOf( 100 ); |
If we look at the valueof () class function, we can see
12345 |
public static integer valueOf ( int i) {        if (i >= integercache.low && i            integercache.cache[i + (-integercache.low)];        return new integer (i);      |
If the value is between 128 and 127, it returns the instance of the cache.
So...
1 |
Integer c = 100 , d = 100 ; |
Both point to the same object.
This is why the result of this code is true:
1 |
System.out.println(c == d); |
Now you might ask, why is the cache set for all integers between 128 and 127?
This is because small numeric integers in this range are used much more frequently in daily life than others, and multiple use of the same underlying object can be used to make efficient memory optimizations through this setting. You can use this feature with the reflection API.
Run the code below and you'll see where it's magical.
12345678910111213 |
public static void main(String[] args)
throws NoSuchFieldException, IllegalAccessException {
Class cache = Integer.
class
.getDeclaredClasses()[
0
];
//1
Field myCache = cache.getDeclaredField(
"cache"
);
//2
myCache.setAccessible(
true
);
//3
Integer[] newCache = (Integer[]) myCache.get(cache);
//4
newCache[
132
] = newCache[
133
];
//5
int a =
2
;
int b = a + a;
System.out.printf(
"%d + %d = %d"
, a, a, b);
//
}
|
Strange Java question: why 1000 = = 1000 returns to False, and 100 = = 100 returns to true?