• Integer 原码解读


    有一天,突然发现,阅读原码可以发现很多有趣的东西。在Java中,我们知道很多东西都是封装好的,拿来即用,当你有一天去研究它拿来的东西是如何具体操作的,将会是非常有趣的事情。

    在上一篇研究HashMap 源码的时候,发现了将任意大于某个数字的最小二次幂的实现,发现别人写的不仅漂亮而且高效。

    在Java 的底层,很多高效的算法包含其中,阅读源码是非常有帮助的。

    接下来将开始阅读 Integer 的源码,让自己更多的理解Integer 这个类的实现。

    一.Integer 中的进制转换,包括将十进制转换为二进制及、八进制、十六进制

      1.调用方法

    Integer.toBinaryString()
    Integer.toOctalString()
    Integer.toHexString()

     2.实现方法

     转换为二进制
    public static String toBinaryString(int i) {
            return toUnsignedString0(i, 1);
        }
     
     转换为八进制
     public static String toOctalString(int i) {
            return toUnsignedString0(i, 3);
        }
    
     转换为十六进制
    public static String toHexString(int i) {
            return toUnsignedString0(i, 4);
        }

     3.底层实现

      发现所有的进制转换都是调用的 toUnsignedString0() 这个方法,其实现如下

     方法调用一
    private static String toUnsignedString0(int val, int shift) {
            // assert shift > 0 && shift <=5 : "Illegal shift value";
            int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
            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);
        }
    
    方法调用二
     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 {
                buf[offset + --charPos] = digits[val & mask];
                val >>>= shift;
            } while (val != 0 && charPos > 0);
    
            return charPos;
        }
    
    方法调用三
    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'
        };

    二. Integer 中的方法

    方法1:比较2个数字的大小,若 第一个小于第二个,返回-1;若相等,返回0;若第一个大于第二个,返回1

     public static int compare(int x, int y) {
            return (x < y) ? -1 : ((x == y) ? 0 : 1);
        }

    方法2:  返回该数字二进制 补码中 1 的个数 

    public static int bitCount(int i) {
            // HD, Figure 5-2
            i = i - ((i >>> 1) & 0x55555555);
            i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
            i = (i + (i >>> 4)) & 0x0f0f0f0f;
            i = i + (i >>> 8);
            i = i + (i >>> 16);
            return i & 0x3f;
        }

    方法3: 返回String 或者 int 类型的 Integer 实例

    第一步:
    public static Integer valueOf(String s) throws NumberFormatException {
            return Integer.valueOf(parseInt(s, 10));
        }
    
    第二步:
    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) {
                    // Accumulating negatively avoids surprises near MAX_VALUE
                    digit = Character.digit(s.charAt(i++),radix);
                    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;
                }
            } else {
                throw NumberFormatException.forInputString(s);
            }
            return negative ? result : -result;
        }
    
    第三步:
     public static Integer valueOf(int i) {
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }

    方法4:将String 类型转换为 Int 类型

    输入String 
     public static int parseInt(String s) throws NumberFormatException {
            return parseInt(s,10);
        }

      parseInt() 调用方法同上
  • 相关阅读:
    保存ADO的记录集为XML文件
    [C++] Undefined reference to vtable
    Csdn博客的一个bug
    深入解析ATL(第二版ATL8.0)(1.111.13节)
    不同操作系统下记事本的换行符号
    dom4j学习总结(一)
    关于firefox的copy/paste的问题
    php URL编码解码函数
    php连接MySQL数据库的一些问题
    使用 jQuery progressBar 做文件上传的进度条指示
  • 原文地址:https://www.cnblogs.com/baizhuang/p/10190032.html
Copyright © 2020-2023  润新知