See: http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt346
This is a very interesting discussion topic.
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'll get
Basic knowledge: We know that if two references point to the same object, = = to indicate that they are equal. If two references point to different objects, use = = to indicate that they are not equal, even if their contents are the same.
Therefore, the following statement should also be false.
That's where it's interesting. If you look at the Integer.java class, you will find an internal private class, Integercache.java, which caches all the integer objects from 128 to 127.
So the thing is, all the small integers are cached inside, and then when we declare something like--
When it's actually done inside is
1 |
Integer i = Integer.valueOf( 100 ); |
Now, if we go to see the valueof () method, we can see
12345 |
public static < Code class= "Java Plain" >integer valueof ( int i) { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; if (i >= integercache.low && i return integercache.cache[i + (-integercache.low)]; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; return new integer (i); &NBSP;&NBSP;&NBSP;&NBSP; } |
If the value ranges from 128 to 127, it returns the instance from the cache.
So...
1 |
Integer c = 100 , d = 100 ; |
Points to the same object.
That's why we write
1 |
System.out.println(c == d); |
We can get the true.
Now you might ask, why do I need a cache here?
The logical reason is that the "small" integer usage in this range is higher than a large integer, so using the same underlying object is valuable and can reduce the potential memory footprint.
However, you will misuse this feature through the reflection API.
Run the code below and enjoy its charms.
12345678910 |
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);
//
}
|
Why is 1000==1000 in Java two integers false and 100==100 true?