An interesting interview question about the Integer class

ca54f0add9624c9885ea426864c0bbe2.png

     I believe that many people think that the answer is false, false, because Integer is a class, passing int type data to Integer type data will create an object, and a, b, c, d as references point to different addresses, so The result of judging the same should be false

    But this idea is exactly what I wanted, and the result is actually true, false

    why? Because converting int type data to Integer type requires calling the static method valueOf in the Integer class, and the internal implementation of the valueOf method is as follows:

5f016beb4b1d4fde9f0c9169fbbb03a1.png

    The simple explanation is that the int type data in the range of -128 to 127 needs to be converted, and the data stored in the array can be directly called, and a new object is recreated if it is not in this range, so 127 is in this range. The reference can directly point to the existing data in the array, so the value of the reference is the same, but if 128 is not in this range, the object needs to be recreated, so the objects pointed to by the two references are different, and the values ​​are also different 

Guess you like

Origin blog.csdn.net/q322359/article/details/131879707