Why is 1000==1000 in Java false and 100==100 true?
This is a very interesting discussion topic.
If you run the following code:
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--
Now, if we go to see the valueof () method, we can see:
If the value ranges from 128 to 127, it returns the instance from the cache.
So...
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.
Why is 1000==1000 in Java false and 100==100 true?
This is a very interesting discussion topic.
If you run the following code:
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--
Now, if we go to see the valueof () method, we can see:
If the value ranges from 128 to 127, it returns the instance from the cache.
So...
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.
Why is 1000==1000 in Java false and 100==100 true?