Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Caused by automatic packing and unpacking, I look at the Integer source code

Shulou Source: shulou.com Published: 2022-06-01 05:15:46 10月03日 Update

Background and problems

When you look at the data compiled by others, you see the following code:

Package com.sitech.test;/**

* automatic boxing and unpacking jdk1.6

* @ author liaowp

* * / public class TestInteger {public static void main (String [] args) {

Integer i1 = 80, i2 = 80, i3 = 999, i4 = 999

System.out.println (i1 = = i2); / / true

System.out.println (i3 = = i4); / / false}

}

If you haven't seen the source code, you must think the answer is either 2 true or 2 false. When I first saw this piece of code, I also thought it was 2 true, and I felt 100% sure, but after I really ran it, I found that I was dumbfounded, one true and one false. This is Bug. In fact, LZ has seen part of the Integer source code before, but now it seems that I don't take it seriously and embarrassed. So this problem triggered LZ to take a serious look at the Integer source code (I want to be serious, ).

Let's go back to the above problem and solve the problem first. We are playing nb. We can see that the four variables in the above code are all references to Integer, so the output = = operation compares not the Integer value but the Integer reference. What is the nature of packing? When we assign an int value to an Integer object, we call the static method valueOf of the Integer class, and we can see why there is such a result by looking at the valueOf method.

/ * *

* Returns an {@ code Integer} instance representing the specified

* {@ code int} value. If a new {@ code Integer} instance is not

* required, this method should generally be used in preference to

* the constructor {@ link # Integer (int)}, as this method is likely

* to yield significantly better space and time performance by

* caching frequently requested values.

*

* This method will always cache values in the range-128 to 127

* inclusive, and may cache other values outside of this range.

*

* @ param i an {@ code int} value.

* @ return an {@ code Integer} instance representing {@ code I}.

* @ since 1.5 * /

Public static Integer valueOf (int I) {/ / is a static method IntegerCache is an inner class assert IntegerCache.high > = 127 if / assertion reference http://lavasoft.blog.51cto.com/62575/43735/ if (I > = IntegerCache.low & & I

Tags: Cache code problem static method source code object facet boxing maximum minimum array time maximum range or maximum frequent awkward three Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Shulou Tech Info NVidia vpn Microsoft