preface

  • Today, I met a pit in the company, and was cursed by the manager. He said, why do I even do a simple comparison work badly?
  • Just received this question I was a face confused, how can I even can not compare? Open the code to locate one or two integers with ==

Knowledge comb

  • Build 128 into two Integer objects. Do you think they are the same
  • Build 127 into two Integer objects. Do you think they are the same
public static void main(String[] args) throws InterruptedException {
    Integer i1=128;
    Integer i2=128;
    Integer i3=127;
    Integer i4=127;
    System.out.println(i1==i2);
    System.out.println(i3==i4);
}
Copy the code

The manager to teach

  • The final output of the above program is respectivelyfalse,true
  • Why does the same operation get different results? I really don’t see any difference except the value difference
  • Right! It’s a question of value. Because different values lead to different results.

Cache master IntegerCache

  • Such a class exists within IntegerIntegerCacheHis role is to guideIntegerThe data is cached.

  • Let’s take a look at his source code for an explanation of this class. He will beIntegerData of -128 to 127 is cached.
  • In other words, data outside this range is considered cold data. No caching. The cache here is equal toStringDo the same for constant pools.
  • So the topInteger i1=128; Integer i2=128. It’s actually two objects in the heap. Because 128 is out of range and I don’t swap out
  • whileInteger i3=127; Integer i4=127It’s in cache so both variables point to the same block of address.
  • This explains why one is false and one is true.

Xiao li said

  • Why do you do this in Java?
    • A: This is definitely designed to save memory. The inclusion of the cache prevents data in this range from being created repeatedly in the heap
  • It can be passed after java6XX:AutoBoxCacheMax=numTo set theIntegerCacheThe upper limit of the interval.
  • Integer i =100Will automatically box 100 intoIntegerObject is calledInteger.valueOfMethods.
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
Copy the code
  • This is the boxing operation in the Integer class. IntegerCache implements the scope of the subject content cache for this article.

  • Unpacking: Automatic unpacking is the conversion of the package type to the basic data type. The automatic unboxing calls integer.intValue (),

  • Boxing: Automatic boxing is the conversion of the base data type to the packaging type. The automatic boxing procedure calls integer.valueof (int), which is fetched from the Integer constant pool when int is in the range -128 to 127, and produces an Integer object through new when int is outside the range. Easy to cause OOM