zoukankan      html  css  js  c++  java
  • JDK源码分析:Integer.java部分源码解析

    1)声明部:

    public final class Integer extends Number implements Comparable<Integer> 
    

      extends Number, 重写方法:

    public byte byteValue() {  
        return (byte)value;  
    }  
    public short shortValue() {  
        return (short)value;  
    }  
    public int intValue() {  
        return value;  
    }  
    public long longValue() {  
        return (long)value;  
    }  
    public float floatValue() {  
        return (float)value;  
    }  
    public double doubleValue() {  
        return (double)value;  
    } 
    

      implements Comparable<T>,接口实现如下:

    public int compareTo(Integer anotherInteger) {  
        return compare(this.value, anotherInteger.value);  
    } 
    public static int compare(int x, int y) {  
        return (x < y) ? -1 : ((x == y) ? 0 : 1);  
    }
    

      与实现该接口无关观察compareUnsigned方法:

      compareUnsigned 例子:

    Integer a1 = 0b00000000000000000000000000000001;  
    Integer a2 = 0b00000000000000000000000000000011;  
    Integer a3 = 0b10000000000000000000000000000001;  
    Integer a4 = 0b10000000000000000000000000000011;  
    int r1 = Integer.compareUnsigned(a1.intValue(),a2.intValue());  
    int r2 = Integer.compareUnsigned(a1.intValue(),a3.intValue());  
    int r3 = Integer.compareUnsigned(a3.intValue(),a4.intValue());  
    Out.println("a1,a2,a3,a4分别为:" + a1 +"," + a2 + "," + a3 + "," + a4);  
    Out.println("r1,r2,r3分别为:" + r1 +"," + r2 + "," + r3);  
    

      result:

    a1,a2,a3,a4分别为:1,3,-2147483647,-2147483645  
    r1,r2,r3分别为:-1,-1,-1  
    

      算法分析:比较是无符号比较方法,而默认是有符号整型,所以需要特殊方法处理。先看Integer的范围:
      0B10000000000000000000000000000000
      0B10000000000000000000000000000001
      ..
      0B11111111111111111111111111111111
      ...
      0B00000000000000000000000000000000
      0B00000000000000000000000000000001
      0B00000000000000000000000000000010
      ...
      0B01111111111111111111111111111111

      在同一个符号下:除符号位其他位的数字越大,那么该数字越大。+MIN.VALUE就是修改符号位。不影响同一个符号位下的大小比较,
      假设a=-1,b=1按无符号考虑:a>b;
      按有符合考虑:a<b,通过修改符号位,a+MIN.VALUE(正数)>b+MIN.VALUE(负数)
      实现了无符号比较。

    2)属性

    @Native public static final int   MIN_VALUE = 0x80000000;  
    @Native public static final int   MAX_VALUE = 0x7fffffff;  
    /** 
     * The {@code Class} instance representing the primitive type {@code int}. 
     */  
    public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");  
    /** 
     * All possible chars for representing a number as a String 
     */  
    final static char[] digits = {  
        '0' , '1' , '2' , '3' , '4' , '5' ,  
        '6' , '7' , '8' , '9' , 'a' , 'b' ,  
        'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,  
        'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,  
        'o' , 'p' , 'q' , 'r' , 's' , 't' ,  
        'u' , 'v' , 'w' , 'x' , 'y' , 'z'  
    };  
    //十位上的数值,可以根据36,取的十位上数为3  
    final static char [] DigitTens = {  
        '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',  
        '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',  
        '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',  
        '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',  
        '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',  
        '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',  
        '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',  
        '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',  
        '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',  
        '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',  
    } ;  
    //个位上的数值,可以根据36,取的个位上数为6  
    final static char [] DigitOnes = {  
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
    } ;  
    final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,99999999, 999999999, Integer.MAX_VALUE };  
    //避免除法操作,直接比较大小返回位数  
    static int stringSize(int x) {  
        for (int i=0; ; i++)  
            if (x <= sizeTable[i])  
                return i+1;  
    }  
    public Integer(int value) { this.value = value;}  
    @Native public static final int SIZE = 32;  
    public static final int BYTES = SIZE / Byte.SIZE; 
    

      3)内部私有类

    private static class IntegerCache {  
        static final int low = -128;  
        static final int high;  
        static final Integer cache[];  
      
        static {  
            <span style="color:#ff0000;">// high value may be configured by property</span>  
            int h = 127;  
            String integerCacheHighPropValue =  
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");  
            if (integerCacheHighPropValue != null) {  
                try {  
                    int i = parseInt(integerCacheHighPropValue);  
                    i = Math.max(i, 127);  
                    // Maximum array size is Integer.MAX_VALUE  
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);  
                } catch( NumberFormatException nfe) {  
                    // If the property cannot be parsed into an int, ignore it.  
                }  
            }  
            high = h;  
      
            cache = new Integer[(high - low) + 1];  
            int j = low;  
            for(int k = 0; k < cache.length; k++)  
                cache[k] = new Integer(j++);  
      
            // range [-128, 127] must be interned (JLS7 5.1.7)  
            assert IntegerCache.high >= 127;  
        }  
      
        private IntegerCache() {}  
    }  
    

      和Short.java和Byte.java一样,都是通过静态代码块初始化缓存对象数组,不过,IntegerCache对象的high可以通过JVM的启动参数设置,缺省为127。

    4)初始化方法

      构造函数:

    public Integer(String s) throws NumberFormatException {  
        this.value = parseInt(s, 10);  
    }  
    public Integer(int value) {  
        this.value = value;  
    }
    

       其他方法:

    public static int parseInt(String s, int radix);  
    public static int parseInt(String s) throws NumberFormatException;  
    public static Integer valueOf(String s, int radix) throws NumberFormatException;   
    public static Integer valueOf(String s) throws NumberFormatException;  
    public static Integer valueOf(int i);  
    public static int parseUnsignedInt(String s) throws NumberFormatException;  
    public static int parseUnsignedInt(String s, int radix);
    

      观察“其他方法”的代码,难点主要在下面的方法:

    public static int parseInt(String s, int radix)  
                throws NumberFormatException  
    {  
        /* 
         * WARNING: This method may be invoked early during VM initialization 
         * before IntegerCache is initialized. Care must be taken to not use 
         * the valueOf method. 
         */  
      
      
        if (s == null) {  
            throw new NumberFormatException("null");  
        }  
      
      
        if (radix < Character.MIN_RADIX) {  
            throw new NumberFormatException("radix " + radix +  
                                            " less than Character.MIN_RADIX");  
        }  
      
      
        if (radix > Character.MAX_RADIX) {  
            throw new NumberFormatException("radix " + radix +  
                                            " greater than Character.MAX_RADIX");  
        }  
      
      
        int result = 0;  
        boolean negative = false;  
        int i = 0, len = s.length();  
        int limit = -Integer.MAX_VALUE;  
        int multmin;  
        int digit;  
      
      
        if (len > 0) {  
            char firstChar = s.charAt(0);  
            if (firstChar < '0') { // Possible leading "+" or "-"  
                if (firstChar == '-') {  
                    negative = true;  
                    limit = Integer.MIN_VALUE;  
                } else if (firstChar != '+')  
                    throw NumberFormatException.forInputString(s);  
      
      
                if (len == 1) // Cannot have lone "+" or "-"  
                    throw NumberFormatException.forInputString(s);  
                i++;  
            }  
            multmin = limit / radix;//设不同进制下的极限值  
            while (i < len) {  
    <span style="color:#ff0000;">           // Accumulating negatively avoids surprises near MAX_VALUE  
                //该方法返回该字符根据进制对应的数字,比如2进制1那么返回1,比如16进制F那么返回15  
                digit = Character.digit(s.charAt(i++),radix);//i++:0->1  
                if (digit < 0) {  
                    throw NumberFormatException.forInputString(s);  
                }  
                if (result < multmin) {  
                    throw NumberFormatException.forInputString(s);  
                }  
                result *= radix;  
                if (result < limit + digit) {  
                    throw NumberFormatException.forInputString(s);  
                }  
                result -= digit;</span>  
            }  
        } else {  
            throw NumberFormatException.forInputString(s);  
        }  
        return negative ? result : -result;  
    }  
    

      

    该代码段例子分析:

    F1F(16进制)

           (1)digit 15;result *= radix -》0;result -= digit -》 -15 
                        (2)digit 1;result *= radix -》-15*16;result -= digit -》 -15*16 - 1(相当于累加) 
                        (3)digit 15;result *= radix -》-(15*16+1)*16;result -= digit -》 -(15*16+1)*16 - 15
                        (4)-( -(15*16+1)*16 - 15)= (15*15+1)*16 + 15

        public static int parseUnsignedInt(String s, int radix)
                    throws NumberFormatException {
            if (s == null)  {
                throw new NumberFormatException("null");
            }
    
            int len = s.length();
            if (len > 0) {
                char firstChar = s.charAt(0);
                if (firstChar == '-') {
                    throw new
                        NumberFormatException(String.format("Illegal leading minus sign " +
                                                           "on unsigned string %s.", s));
                } else {
                    if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits
                        (radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits
                        return parseInt(s, radix);
                    } else {
                        long ell = Long.parseLong(s, radix);
                        if ((ell & 0xffff_ffff_0000_0000L) == 0) {
                            return (int) ell;
                        } else {
                            throw new
                                NumberFormatException(String.format("String value %s exceeds " +
                                                                    "range of unsigned int.", s));
                        }
                    }
                }
            } else {
                throw NumberFormatException.forInputString(s);
            }
        }
    

      例子:

    Integer a11 = 3;  
    Integer a6 = Integer.parseInt("11",2);  
    Integer a7 = Integer.parseUnsignedInt("80000000",16);  
    Integer a9 = Integer.valueOf(3);  
    Integer a10 = new Integer(3);  
    boolean b1 = a6==a9;//true  
    boolean b2 = a6==a11;//true  
    boolean b3 = a6==a10;//false
    

      初始化对象进行使用parseInt或者valueOf方法,如果值在IntegerCache范围内,可以直接获取对象。

    5)一些toXXXString方法:

    public static String toString(int i, int radix) {  
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)  
            radix = 10;  
      
        /* Use the faster version */  
        if (radix == 10) {  
            return toString(i);  
        }  
      
        char buf[] = new char[33];//二进制  
        boolean negative = (i < 0);  
        int charPos = 32;  
      
        if (!negative) {  
            i = -i;  
        }  
      
        while (i <= -radix) {  
            buf[charPos--] = digits[-(i % radix)];  
            i = i / radix;  
        }  
        buf[charPos] = digits[-i];  
      
        if (negative) {  
            buf[--charPos] = '-';  
        }  
            //从buf数组的charPos位置开始截取33-charPos字符转换为String类型  
        return new String(buf, charPos, (33 - charPos));  
    }  
    

      分析该函数之前,我们用十进制转换为二进制来解释下算法:比如10,10%2 商5余0;5%2 商2余1;2%2 商1余0;2%1 商0余1,把余数倒序拼接1010,1010就是二进制。i++号在后面的意思是先赋值然后自身加1;++i在前面的是先自身加1后赋值;--同样。

    public static String toUnsignedString(int i, int radix);  
    public static String toHexString(int i);  
    public static String toOctalString(int i);  
    public static String toBinaryString(int i){  
        return toUnsignedString0(i, 1);  
    }  
      
    //前面4个方法都是调用该方法,shift:次幂  
    private static String toUnsignedString0(int val, int shift) {  
        // assert shift > 0 && shift <=5 : "Illegal shift value";  
        //获取有效的二进制的位数 31位二进制  
        int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);  
        //一个算法,可以根据二进制的有效位数,求出8进制或者16进制的位数  
        //比如0100 0000 shift=3 -》 (7+(3-1))/3 = 3 八进制需要3位表示  
        int chars = Math.max(((mag + (shift - 1)) / shift), 1);  
        char[] buf = new char[chars];  
      
        formatUnsignedInt(val, shift, buf, 0, chars);  
      
        // Use special constructor which takes over "buf".  
        return new String(buf, true);  
    }  
      
    //转换为2进制,高位-》低位,直至遇到1停止,0的个数  
    //比如0000 0000 0000 0000 0000 0000 0000 0001-》31  
    //比如0100 0000 0000 0000 0000 0000 0000 0001-》1  
    //比如0010 0000 0000 0000 0000 0000 0000 0001-》2  
    public static int numberOfLeadingZeros(int i) {  
        // HD, Figure 5-6  
        if (i == 0)  
            return 32;  
        int n = 1;  
        if (i >>> 16 == 0) { n += 16; i <<= 16; }  
        if (i >>> 24 == 0) { n +=  8; i <<=  8; }  
        if (i >>> 28 == 0) { n +=  4; i <<=  4; }  
        if (i >>> 30 == 0) { n +=  2; i <<=  2; }  
        n -= i >>> 31;  
        return n;  
    }  
      
    static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {  
        int charPos = len;  
        int radix = 1 << shift;  
        int mask = radix - 1;  
        do {  
            //val&mask 可以获取末尾使用该进制表示的数值  
            //例子 假设16进制  
            //  1010 1010 1010 1000  
            //& 0000 0000 0000 1111  
            //  0000 0000 0000 1000  
            buf[offset + --charPos] = Integer.digits[val & mask];  
            val >>>= shift;  
        } while (val != 0 && charPos > 0);  
        return charPos;  
    }  
    

      

    public static String toString(int i) {  
        if (i == Integer.MIN_VALUE)  
            return "-2147483648";  
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);  
        char[] buf = new char[size];  
         // 将Integer数读入到char[]数组  
        getChars(i, size, buf);  
        return new String(buf, true);  
    }  
    static void getChars(int i, int index, char[] buf) {  
        int q, r;  
        int charPos = index;  
        char sign = 0;  
      
        if (i < 0) {  
            sign = '-';  
            i = -i;  
        }  
      
        // Generate two digits per iteration  
        // 处理超过2的16次方的大数  
        while (i >= 65536) {  
            q = i / 100;  
            // really: r = i - (q * 100);  
            // 假设 65536 那么等于 36,根据36取的十位数和个位数上的数值         
            r = i - ((q << 6) + (q << 5) + (q << 2));  
            //655  
            i = q;  
            //个位 6  
            buf [--charPos] = DigitOnes[r];  
            //十位 3  
            buf [--charPos] = DigitTens[r];  
        }  
      
        // Fall thru to fast mode for smaller numbers  
        // assert(i <= 65536, i);  
        // 处理<2的16次方的大数  
        for (;;) {  
            q = (i * 52429) >>> (16+3);//i*52429/524288 ≈0.1000003。相当于i/10  
            //获取个位的数字  
            r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...  
            buf [--charPos] = digits [r];  
            i = q;  
            if (i == 0) break;  
        }  
        if (sign != 0) {  
            buf [--charPos] = sign;  
        }  
    } 
    

     一个例子: 

    for(int i = 0;i<65536;i++){  
        int q = (i * 52429) >>> (16+3);//相当于q = i/10;  
        int j = i/10;  
        if(q != j){  
            Out.println(false);  
        }  
    } 
    输出:true
    

      

  • 相关阅读:
    mysql存储过程
    命令简写 ~/.bash_aliases
    TestCafe 快速上手 (三)
    TestCafe 快速上手 (二)
    OWASP 文档
    读书笔记
    读书笔记
    类数组转化为真正的数组
    Vue子组件向父组件传递数据
    node.js取参四种方法req.body,req.params,req.param,req.body
  • 原文地址:https://www.cnblogs.com/knsbyoo/p/9032563.html
Copyright © 2011-2022 走看看