JDK Source Code Analysis-integer

Source: Internet
Author: User
Tags comparable

  Integer is usually one of the most commonly used classes in development, but if you have not studied the source of many features and pits may not know, the following in-depth source to analyze the design and implementation of the integer.

Integer:

Inheritance structure:

-Java.lang.Object

--java.lang.number

---java.lang.Integer

Where the parent class number is an abstract class, which is the parent class for all the numeric types related to the class, such as,, Double Float ,, Integer Long andShort。

The integer class also implements the comparable interface to compare the size of two integers.

// Source Code  Public Final class extends Implements Comparable<integer>

The integer class specifies a range of large hours between -2^31~2^31-1.

    //Source Code    /*** A constant holding the minimum value an {@codeint} can * has, -2<sup>31</sup>. */@Native Public Static Final intMin_value = 0x80000000; /*** A constant holding the maximum value an {@codeint} can * has, 2<sup>31</sup>-1. */@Native Public Static Final intMax_value = 0x7fffffff;

There is also a size field that represents the number of bits of the int value in twos complement form, representing the int type field of the instance of the base type Class .

  Internal method implementation:

  Integer probably implemented forty or fifty methods, the following combined with the source code analysis of the usual and more important methods.

First, an integer object is constructed , and the integer construction method is simply passed in an int or string directly. The incoming int is directly assigned to the Value field to save. Passing in a string first converts s through the parseint method to a decimal int and then assigns a value to the Value field.

    // Source Code     Public Integer (int  value) {        this. Value = value;    }       Public throws numberformatexception {        this. Value = parseint (S, ten);    } 

Let's take a look at this not-so-simple parseint method.

It can be seen from the method signature that the function of this method is to parse the string that is passed into the radix mechanism into a decimal int value. And some exception handling has been done. Give me a chestnut:

parseint ("0", ten) returns 0parseint ("473", returns 473parseint ("+42", ten) returns 42parseint ("-0", ten) returns 0parseint ("-ff", returns-255parseint ("1100110", 2) returns 102parseint ("2147483647", returns 2147483647parseint (" -2147483648", returns-2147483648parseint ("2147483648", 10)throwsa numberformatexception parseint ("99", 8)throwsa numberformatexception parseint ("Kona", 10)throwsa numberformatexception parseint ("Kona", returns 411787

Here's a look at the implementation (for a clearer analysis of the implementation process, the text is written as a comment in the source code):

//source code, limited to the length of simplified source format.      Public Static intparseint (String S,intRadixthrowsNumberFormatException {//here is the warning because the ValueOf method uses the Parseint method and the Integercache object,//because valueof is used before Integercache initialization causes an exception condition. Detailed analysis will be later.         /** Warning:this method may be invoked early during VMS initialization * before Integercache is initial Ized.         Care must is taken to does use * the ValueOf method. */        //The following three if are used to determine whether a parameter is valid. The radix size is between 2~36.         if(s = =NULL) {            Throw NewNumberFormatException ("null"); }        if(Radix <Character.min_radix) {            Throw NewNumberFormatException ("radix" + radix + "less than Character.min_radix"); }        if(Radix >Character.max_radix) {            Throw NewNumberFormatException ("radix" + radix + "greater than Character.max_radix"); }        intresult = 0;//parsing Results        BooleanNegative =false;//whether it is a negative number        inti = 0, Len = s.length ();//index variable and string length        intLimit =-integer.max_value;//Maximum value limit        intMultmin;//minimum value under base        intDigit//record the number of each digit        if(Len > 0) {            CharFirstchar = S.charat (0); if(Firstchar < ' 0 ') {//judging whether to take ' + ' or '-'                if(Firstchar = = '-')) {Negative=true; Limit=Integer.min_value; } Else if(Firstchar! = ' + '))                    Thrownumberformatexception.forinputstring (s); if(len = = 1)//the format is illegal and contains characters other than ' + '-'.                     Thrownumberformatexception.forinputstring (s); I++; } multmin= Limit/Radix;  while(I <Len) {                //The use of digit in the character class is illegal, and the function is to parse a character. digit = Character.digit (S.charat (i++), radix); //make exception judgments. //This parsing string for the number of algorithms and usually think of the same, is starting from the left of the string, the initialization result is 0,//In fact, the results are calculated negative, return to the time to turn back. Result-= digit;                if(Digit < 0) {                    Thrownumberformatexception.forinputstring (s); }                if(Result <multmin) {                    Thrownumberformatexception.forinputstring (s); } result*=Radix; if(Result < limit +Digit) {                    Thrownumberformatexception.forinputstring (s); } result-= digit;            }        } Else {            Thrownumberformatexception.forinputstring (s); }        returnNegative? Result:-result;//if it is negative, return it directly, because the calculated number is already negative. }

Integer.parseint (String s), which is often used in peacetime, is also based on this method. Only the default radix is 10.

// Source    Code  Public Static int throws numberformatexception {        return parseint (s,10);    }  

The next step is to analyze the valueof method mentioned above. A total of three valueof methods, only the different parameters. There are two internal implementations that are based on valueof (int i) and parseint (String s, int radix).

Source
public staticintthrows numberformatexception { return Integer.valueof (parseint (S,radix)); } Public Static throws numberformatexception { return integer.valueof (parseint (S)); }

So let's analyze the valueof (int i) method.

Source
publicstatic Integer valueOf (int i) { if (i >= integercache.low && Amp I <= integercache.high) return integercache.cache[i + (-integercache.low)]; return New Integer (i); }

You can see that the Integercache cache is used here, Integercache the integer between the default cache -128~127. Integercache is the static inner class of the integer class.

//Source CodePrivate Static classIntegercache {Static Final intLow =-128;//default low=-128    Static Final intHigh//High can be configured through the VM parameter-xx:autoboxcachemax=<size>//High can be configured, so the default cache is -128~127, but other common numbers can be cached.     Static FinalInteger cache[];//Cache Array//static code blocks, which are cached when the integer class is loaded.     Static {        //High value is configured by property        inth = 127;//Default 127String Integercachehighpropvalue =Sun.misc.VM.getSavedProperty ("Java.lang.Integer.IntegerCache.high");//read the VM parameter configuration.         if(Integercachehighpropvalue! =NULL) {            Try {                inti =parseint (Integercachehighpropvalue); I= Math.max (i, 127);//Cache Large Number//Maximum array size is Integer.max_valueh = math.min (i, Integer.max_value-(-low)-1);//prevent cross-border}Catch(NumberFormatException nfe) {//If The property cannot is parsed into an int, ignore it.}} High=h; Cache=Newinteger[(high-low) + 1];//creates a cache array.         intj =Low ;  for(intk = 0; K < Cache.length; k++) Cache[k]=NewInteger (j + +);//Cache. //range [ -128, 127] must be interned (JLS7 5.1.7)        assertIntegercache.high >= 127;//guaranteed [-128, 127] within the cache range.     }    PrivateIntegercache () {}}

Let's look at a test code:

  
First, make it clear that the = = between objects is a comparison of memory addresses, and comparisons between constants are numeric comparisons.
Public Static voidMain (string[] args) {Integer num1=NewInteger (100); Integer num2=NewInteger (100); System.out.println (NUM1 = =num2);//false, because the two objects are created independently and have their own memory space and address. Integer num3= 100; Integer num4= 100; System.out.println (NUM3 = =num4);//true, comparing values between constants. Integer NUM5= 128; Integer NUM6= 128; System.out.println (NUM5 = =num6);//false, automatically boxed into objects, but exceeds the default cache range, the same as the first one. If 127 is true. Integer Num7= 100; Integer NUM8=NewInteger (100); System.out.println (Num7 = =num8);//false, two objects compare memory addresses, the difference is num7 through automatic boxing call valueof method, point to the cache of 100, and NUM8 is pointing to its own memory space of 100. intNUM9 = 100; Integer NUM10=NewInteger (100);
System.out.println (num9 = = NUM10); When the//true,integer object is compared to int, the integer automatically unboxing (Intvalue method) becomes int, which becomes a two numeric comparison. Integer NUM11= 100;System.out.println (NUM9 = =NUM11);//true,num11 calls the ValueOf method by auto-boxing to point to 100 in the cache, when the 100 object in the cache is automatically disassembled as the value 100. }

If you do not carefully study the integer caching mechanism and the automatic unpacking mechanism, the results of this program will definitely surprise you. After understanding, it's OK.

Understanding this caching mechanism is also very important, because if there is a bug in the program because of this, if you do not know the caching mechanism can not be adjusted to death.

Here's a talk about Long,short is similar to the integer mechanism, except that the high configuration is not supported. Double,float does not have a caching mechanism, because even the floating-point numbers between -128~127 are close to infinity.

This time the source code analysis of the integer class here, there are also some of the integer in the inverse code, the complement of the calculation of the method of the bitwise operation. If you are interested in or developing it, use it to study again.

JDK Source code Analysis-integer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.