When comparing two Integer objects, why is 100 equal to 100 and 1000 not equal to 1000?

When comparing two Integer objects, why is 100 equal to 100 and 1000 not equal to 1000?

Inspection point
Integer is a packaging class that we often use in development. Understanding its basics is very important. This question is because the interviewer wants to examine whether we are good at accumulating knowledge in daily life and think carefully about this knowledge!

Regarding this question, my answer is as follows:
1. Let’s look at a specific example:

public boolean xxx(Integer a,Integer b){
    
    
   ...
   if(a==b){
    
    
     return true;
   }
   ...
   return false;
}

a和b输入100,返回的结果是true
a和b输入1000,返回的结果是false

In the above code, when we input a and b both 100, the result is true, but when a and b are 1000, it reports false. What is going on?

2. View the source code valueof method of Integer:


public final class Integer extends Number implements Comparable<Integer>{
    
    
  ...
  public static Integer valueOf(int i){
    
    
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
     return new Integer(i);
     }
 }
通过源码可以看到IntegerCache.cache、和IntegerCache.low、IntegerCache.high在
对数据结果进行影响。

The value of IntegerCache.low is -128 and the value of IntegerCache.high is 127.

That is to say, if the target value is between -128 and 127, the value will be taken directly from the cache array, otherwise a new object will be created. Why is it -128~127? The reason is that data from -128 to 127 is the most frequently used in the int range. In order to reduce the memory consumption caused by frequent object creation, the flyweight mode is actually used here to improve space and time performance.

Guess you like

Origin blog.csdn.net/weixin_45817985/article/details/133063935