JDK1.8源码学习--lang包(Integer)

前言
 


月是一轮明镜,晶莹剔透,代表着一张白纸(啥也不懂)

央是一片海洋,海乃百川,代表着一块海绵(吸纳万物)

泽是一柄利剑,千锤百炼,代表着千百锤炼(输入输出)

月央泽,学习的一种过程,从白纸->吸收各种知识->不断输入输出变成自己的内容

希望大家一起坚持这个过程,也同样希望大家最终都能从零到零,把知识从薄变厚,再由厚变薄!
 

一.Integer的作用:

         直接看源码注释(我的翻译可能不太准,如果道友们有更棒的理解,可以留言或者私信)

/**
 * The {@code Integer} class wraps a value of the primitive type
 * {@code int} in an object. An object of type {@code Integer}
 * contains a single field whose type is {@code int}.
 * 1.Integer类将原始类型int的值包装在一个对象中,Integer类型的对象包含一个类型为int的字段。
 * <p>In addition, this class provides several methods for converting
 * an {@code int} to a {@code String} and a {@code String} to an
 * {@code int}, as well as other constants and methods useful when
 * dealing with an {@code int}.
 * 2.此外,该类还提供了几种将int转换为String和将String转换为int的方法,以及在处理int
 * <p>Implementation note: The implementations of the "bit twiddling"
 * methods (such as {@link #highestOneBit(int) highestOneBit} and
 * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are
 * based on material from Henry S. Warren, Jr.'s <i>Hacker's
 * Delight</i>, (Addison Wesley, 2002).
 * 3.>实施说明:“位旋转”方法(例如highestOneBit(int)和numberOfTrailingZeros(int))
 * 的实现基于来自Henry S. Warren, Jr. 的材料<i>黑客的喜悦<i>,(艾迪生韦斯利,2002 年)
 * @author  Lee Boynton
 * @author  Arthur van Hoff
 * @author  Josh Bloch
 * @author  Joseph D. Darcy
 * @since JDK1.0
 */

二.Integer的类图:

 

  a).一个Comparable,这个接口对实现他的每个对象都可按照一定的规则来进行排序,详情请点击下面链接

       JDK1.8源码学习--lang包(Comparable)_w5_Silence的博客-CSDN博客

    b).Secializable,这个接口是可为实现的对象进行序列化,详情请点击下面链接
                  ......(假装这个是链接,以后补充)

    c).Numer,这个抽象类对一些数字操作进行了相关规范

        JDK1.8源码学习--lang包(Number)_w5_Silence的博客-CSDN博客

  三.成员变量: 

 /**
     * 保持 int 可以具有的最小值的常量,-2的31次方
     */
    @Native public static final int   MIN_VALUE = 0x80000000;

    /**

     * 保持 int 可以具有的最大值的常量,2的31-1
     */
    @Native public static final int   MAX_VALUE = 0x7fffffff;

    /**
     * 表示原始类型int的Class实例
     * @since   JDK1.1
     */
    @SuppressWarnings("unchecked")
    public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");

    /**
     * 将数字表示为字符串的所有可能字符
     */
    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'
    };

 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',
        } ;

    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 };

/**
     * Integer的值。
     */
    private final int value;

/**
     * 用于以二进制补码形式表示 int值的位
     */
    @Native public static final int SIZE = 32;

    /**
     * 用于以二进制补码形式表示 int 值的字节数
     */
    public static final int BYTES = SIZE / Byte.SIZE;

四.内部类: 

                IntegerCache

    /**

     * 1.缓存以支持 JLS 要求的 -128 和 127(含)之间值的自动装箱的对象标识语义

     * 2.缓存在第一次使用时初始化。缓存的大小可以由  -XX:AutoBoxCacheMax=<size> 选项控制。
     * 在VM初始化过程中,java.lang.Integer.IntegerCache.high属性可能会被设置并保存
     * 在sun.misc.VM类的私有系统属性中。
     */

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            //可以通过属性配置高值
            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
                    //最大数组大小为 Integer.MAX_VALU
                    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() {}
    }

五.构造方法: 

   /**
     *   构造一个新分配的 Integer对象,表示指定的 int值
     */
    public Integer(int value) {
        this.value = value;
    }

    /**
     * 构造一个新分配的 Integer对象,该对象表示由String参数指示的int值。
     * 字符串按照  parseInt方法使用的基数 10 的方式完全转换为 int值
     */
    public Integer(String s) throws NumberFormatException {
        this.value = parseInt(s, 10);
    }

六.内部方法: 

                转化为不同进制的字符串形式


    /**

     * 1.返回由第二个参数指定的基数中第一个参数的字符串表示形式。

     * 2.如果基数小于Character.MIN_RADIX或大于Character.MAX_RADIX,则使用基数10

     * 3.如果第一个参数为负,则结果的第一个元素是 ASCII 减号字符 '-' 
     * 。如果第一个参数不是负数,则结果中不会出现符号字符。

     * 4.结果的其余字符表示第一个参数的大小,如果幅度为零,则由单个零字符 '0' 表示;
     * 否则,大小表示的第一个字符将不是零字符

     * 5.以下 ASCII 字符用作数字:
     *      它们是 '\u005Cu0030' 到 '\u005Cu0039' 和 '\u005Cu0061'到 '\u005Cu007A'。
     *      如果 radix} 是 N,则这些字符的第一个N将用作所示顺序的基数-N 数字。
     *      因此,十六进制(基数 16)的数字是0123456789abcdef。

     * 6.如果需要大写字母,可以对结果调用java.lang.String.toUpperCase()方法: 
     */
    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] = '-';
        }

        return new String(buf, charPos, (33 - charPos));
    }

    /**

     * 1.以第二个参数指定的基数中的无符号整数值形式返回第一个参数的字符串表示形式

     * 2.如果基数小于 Character.MIN_RADIX或大于 Character.MAX_RADIX,则使用基数 10。

     * 3.请注意,由于第一个参数被视为无符号值,因此不会打印前导符号字符。

     * 4.如果幅度为零,则用单个零字符表示'0';否则,大小表示的第一个字符将不是零字符

     * 5.基数的行为和用作数字的字符与toString(int, int)相同

     */
    public static String toUnsignedString(int i, int radix) {
        return Long.toUnsignedString(toUnsignedLong(i), radix);
    }

    /**

     * 1.以 16 进制无符号整数形式返回整数参数的字符串表示形式
     * 2.如果参数为负,则无符号整数值是参数加上 2<sup>32<sup>;
     * 否则,它等于参数。此值被转换为十六进制(基数 16)的 ASCII 数字字符串,没有额外的前导 0。

     * 3.通过调用Integer.parseUnsignedInt(String, int),可以从返回的字符串s中恢复参数的值

     * 4.如果无符号幅度为零,则由单个零字符 '0'表示;否则,无符号幅度表示的第一个字符将不是零字符。
     */
    public static String toHexString(int i) {
        return toUnsignedString0(i, 4);
    }

    /**
     * 1.将整数参数的字符串表示形式返回为基数为 8 的无符号整数

     * 2.如果参数为负,则无符号整数值是参数加上 2<sup>32<sup>;否则,它等于参数。
     * 该值被转换为八进制(基数为 8)的 ASCII 数字字符串,没有额外的前导 0
     */
    public static String toOctalString(int i) {
        return toUnsignedString0(i, 3);
    }

    /**
     * 以 2 为基数的无符号整数形式返回整数参数的字符串表示形式。
     *无符号整数值是参数加2<sup>32<sup>,如果参数为负数;否则它等于参数。
     * 此值转换为二进制(基数 2)的 ASCII 数字字符串,没有额外的前导 0。
     */
    public static String toBinaryString(int i) {
        return toUnsignedString0(i, 1);
    }

  /**
     * 返回表示指定整数的  String对象。参数被转换为有符号十进制表示并作为字符串返回,
     * 就像参数和基数 10 作为参数提供给 toString(int, int) 方法一样。
     */
    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];
        getChars(i, size, buf);
        return new String(buf, true);
    }

    /**
     * 以无符号十进制值形式返回参数的字符串表示形式。
     */
    public static String toUnsignedString(int i) {
        return Long.toString(toUnsignedLong(i));
    }

        将字符串解析成所要求的int

   /**
     * 1.将字符串参数解析为第二个参数指定的基数中的有符号整数
     * 2.字符串中的字符必须都是指定基数的数字(由java.lang.Character.digit(char, int)是否返回非负值决定),
     * 除了第一个字符可以是ASCII减号{'-'} 表示负值
     * 或 ASCII 加号 {@code '+'}  表示正值,返回结果整数值
  
     * 3.如果发生以下任何一种情况,则会抛出NumberFormatException类型的异常:
     * 第一个参数是 {@code null} 或长度为零的字符串。
     
     * 4.基数小于 java.lang.CharacterMIN_RADIX或大于 java.lang.CharacterMAX_RADIX
     
     * 5.字符串中的任何字符都不是指定基数的数字,除了第一个字符可以是减号'-'
     * 或加号{@code '+' } 前提是字符串的长度大于长度 1。
   
     */
    public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        /*
     
         * 警告:此方法可能会在 IntegerCache 初始化之前的 VM 初始化期间提前调用。必须注意不要使用 valueOf 方法。
         */

        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
                //负累积避免了 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;
    }

    
     * 将字符串参数解析为有符号十进制整数。
     * 字符串中的字符必须都是十进制数字,除了第一个字符可以是ASCII减号'-'}表示负值
   
     */
    public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }

    /**
     * 1.将字符串参数解析为第二个参数指定的基数中的无符号整数。
     * 无符号整数将通常与负数关联的值映射到大于 MAX_VALUE的正数
   
     * 2.字符串中的字符必须都是指定基数的数字(由java.lang.Character.digit(char, int)是否返回非负值决定),
     * 除了第一个字符可以是ASCII加号'+'。返回结果整数值
     *
     * 字符串的任何字符都不是指定基数的数字,但第一个字符可以是加号'+',前提是该字符串的长度大于长度 1

     * 字符串表示的值大于最大的无符号int,2<sup>32<sup>-1。

     */
    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);
        }
    }

    /**
   
     * 将字符串参数解析为无符号十进制整数。字符串中的字符必须都是十进制数字,
     * 除了第一个字符可以是ASCII加号'+'。返回结果整数值,就像参数和基数 10 
     * 作为参数提供给parseUnsignedInt(java.lang.String, int)方法一样。
     */
    public static int parseUnsignedInt(String s) throws NumberFormatException {
        return parseUnsignedInt(s, 10);
    }

                各种类型的值相互转化

    /**
     * 1.返回一个 Integer对象,该对象保存从指定的String中提取的值,当使用第二个参数给出的基数进行解析时。
     * 第一个参数被解释为表示由第二个参数指定的基数中的有符号整数,就像将参数提供给 parseInt(java.lang.String, int)方法一样。
     * 结果是一个 Integer 对象,表示字符串指定的整数值
     * 2.换句话说,这个方法返回一个Integer对象,其值等于:new 
     */
    public static Integer valueOf(String s, int radix) throws NumberFormatException {
        return Integer.valueOf(parseInt(s,radix));
    }

    /**
     * 1.返回一个Integer对象,其中包含指定的String的值。该参数被解释为表示一个带符号的十进制整数,
     * 就像将参数提供给 parseInt(java.lang.String)方法一样。结果是一个Integer对象,表示字符串指定的整数值
     * 2.换句话说,此方法返回一个 Integer对象,其值等于:new 
     */
    public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
    }

  

    /**
     * 1.返回表示指定的int值的Integer实例。如果不需要新的 Integer实例,则通常应优先使用此方法
     * 而不是构造函数 Integer(int),因为此方法可能会通过缓存频繁请求的方式产生明显更好的空间和时间性能值。

     * 2.此方法将始终缓存 -128 到 127(含)范围内的值,并且可能缓存此范围之外的其他值。
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }


    /**

     *   构造一个新分配的 Integer对象,表示指定的 int值

     */
    public Integer(int value) {
        this.value = value;
    }

    /**

     * 构造一个新分配的 Integer对象,该对象表示由String参数指示的int值。
     * 字符串按照  parseInt方法使用的基数 10 的方式完全转换为 int值

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

    /**

     * 在缩小原始转换后,将此Integer的值作为 byte返回。
     */
    public byte byteValue() {
        return (byte)value;
    }

    /**

     * 在缩小原始转换后,将此Integer的值作为short返回
     */
    public short shortValue() {
        return (short)value;
    }

    /**
 
     * 将此 Integer 的值作为 int返回
     */
    public int intValue() {
        return value;
    }

    /**
     * 在扩展原始转换后,将此Integer的值作为long返回。

     */
    public long longValue() {
        return (long)value;
    }

    /**
     * 在扩展原始转换后,将此Integer的值作为float返回
     */
    public float floatValue() {
        return (float)value;
    }

    /**
     * 在扩展原始转换后,将此Integer的值作为 double返回。
     */
    public double doubleValue() {
        return (double)value;
    }

                hashCode

   /**
     *返回此Integer的哈希码
     */
    @Override
    public int hashCode() {
        return Integer.hashCode(value);
    }

    /**
     * 返回int值的哈希码;与 Integer.hashCode() 兼容。
     */
    public static int hashCode(int value) {
        return value;
    }

                equals()

  /**
     *将此对象与指定的对象进行比较。结果是true当且仅当参数不是null
     * 并且是包含与此对象相同的int值的 Integer对象。
   
     */
    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

                getInteger

 /**

     * 1.确定具有指定名称的系统属性的整数值
     * 2.第一个参数被视为系统属性的名称。系统属性可通过java.lang.SystemgetProperty(java.lang.String)方法访问。
     * 然后使用Integer.decode支持的语法将此属性的字符串值解释为整数值,并返回表示此值的Integer对象

     * 3.如果没有指定名称的属性,如果指定名称为空或null,或者如果属性没有正确的数字格式,则返回null。
 
     * 换句话说,此方法返回一个Integer对象,其值等于:getInteger(nm, null)
     */
    public static Integer getInteger(String nm) {
        return getInteger(nm, null);
    }

    /**
     * 1.确定具有指定名称的系统属性的整数值
 
     * 2.第一个参数被视为系统属性的名称。系统属性可通过java.lang.System。getProperty(java.lang.String)方法访问。
     * 然后使用 Integer。decode支持的语法将此属性的字符串值解释为整数值,并返回表示此值的Integer对象。

     * 3.第二个参数是默认值。如果没有指定名称的属性,如果该属性没有正确的数字格式,或者指定的名称为空或  null.
    
     */
    public static Integer getInteger(String nm, int val) {
        Integer result = getInteger(nm, null);
        return (result == null) ? Integer.valueOf(val) : result;
    }

    /**
     * 1.返回具有指定名称的系统属性的整数值。第一个参数被视为系统属性的名称。
     * 系统属性可通过 java.lang.System.getProperty(java.lang.String)方法访问。
     * 然后根据 Integer.decode方法将此属性的字符串值解释为整数值,并返回表示此值的Integer对象
     
     * 2.总之:
     *  1)如果属性值以两个 ASCII 字符 0x或 ASCII 字符 #开头,后面没有减号,
     * 那么它的其余部分将被解析为十六进制整数,就像方法 valueOf(java.lang.String, int) 以 16 为基数。 
     *  2)如果属性值以 ASCII 字符 0开头,后跟另一个字符,则将其解析为八进制整数,
     *  与方法valueOf(java.lang.String, int)以 8 为基数。
     *  3)否则,属性值将被解析为十进制整数,与方法valueOf(java.lang.String, int) 完全一样基数为 10。

     *3.第二个参数是默认值。如果没有指定名称的属性,
     * 如果该属性没有正确的数字格式,或者如果指定的名称为空或null,则返回默认值。
   
     */
    public static Integer getInteger(String nm, Integer val) {
        String v = null;
        try {
            v = System.getProperty(nm);
        } catch (IllegalArgumentException | NullPointerException e) {
        }
        if (v != null) {
            try {
                return Integer.decode(v);
            } catch (NumberFormatException e) {
            }
        }
        return val;
    }

                decode

/**

     * 将  String解码为 Integer。接受语法给出的十进制、十六进制和八进制数

     * 2.DecimalNumeral、HexDigits 和 OctalDigits在Java™ 语言规范的第 3.10.1 节中定义,除了数字之间不接受下划线

     *3.可选符号和/或基数说明符(“0x”、“0X”、“#”或前导零)之后的字符序列被解析为 
     *  Integer.parseInt具有指定基数(10、16 或 8)的方法。此字符序列必须表示正值,
     *  否则将抛出 NumberFormatException。如果指定的 String的第一个字符是减号,则结果否定。 
     *  String中不允许出现空白字符。
     */
    public static Integer decode(String nm) throws NumberFormatException {
        int radix = 10;
        int index = 0;
        boolean negative = false;
        Integer result;

        if (nm.length() == 0)
            throw new NumberFormatException("Zero length string");
        char firstChar = nm.charAt(0);
        // Handle sign, if present
        if (firstChar == '-') {
            negative = true;
            index++;
        } else if (firstChar == '+')
            index++;

        // Handle radix specifier, if present
        if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
            index += 2;
            radix = 16;
        }
        else if (nm.startsWith("#", index)) {
            index ++;
            radix = 16;
        }
        else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
            index ++;
            radix = 8;
        }

        if (nm.startsWith("-", index) || nm.startsWith("+", index))
            throw new NumberFormatException("Sign character in wrong position");

        try {
            result = Integer.valueOf(nm.substring(index), radix);
            result = negative ? Integer.valueOf(-result.intValue()) : result;
        } catch (NumberFormatException e) {
            // If number is Integer.MIN_VALUE, we'll end up here. The next line
            // handles this case, and causes any genuine format error to be
            // rethrown.
            String constant = negative ? ("-" + nm.substring(index))
                                       : nm.substring(index);
            result = Integer.valueOf(constant, radix);
        }
        return result;
    }

                compare

    /**
     * 以数字方式比较两个 Integer对象。
     */
    public int compareTo(Integer anotherInteger) {
        return compare(this.value, anotherInteger.value);
    }

    /**
     * 以数字方式比较两个int值。返回的值与以下返回的值相同:Integer.valueOf(x).compareTo(Integer.valueOf(y)) 
     */
    public static int compare(int x, int y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }

    /**
     * 比较两个 {@code int} 值,以数字方式将这些值视为无符号。
     */
    public static int compareUnsigned(int x, int y) {
        return compare(x + MIN_VALUE, y + MIN_VALUE);
    }

                无符号处理

 /**
     * 1.通过无符号转换将参数转换为long。在到 long的无符号转换中,
     * long的高 32 位为零,低 32 位等于整数参数的位。

     * 2.因此,零和正int值被映射到一个数值相等的long值,负 int值被映射到一个 long值等于输入加上 2的32次方
     */
    public static long toUnsignedLong(int x) {
        return ((long) x) & 0xffffffffL;
    }

    /**
 
     * 1.返回第一个参数除以第二个参数的无符号商,其中每个参数和结果被解释为无符号值。

     * 2.请注意,在二进制补码算术中,如果将两个操作数都视为有符号或无符号,
     * 则加、减和乘这三个其他基本算术运算在位上相同。因此不提供单独的 addUnsigned等方法。

     */
    public static int divideUnsigned(int dividend, int divisor) {
        // In lieu of tricky code, for now just use long arithmetic.
        //代替棘手的代码,现在只使用长算术
        return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor));
    }

    /**
     * 返回第一个参数除以第二个参数的无符号余数,其中每个参数和结果被解释为无符号值。
     */
    public static int remainderUnsigned(int dividend, int divisor) {
        // In lieu of tricky code, for now just use long arithmetic.
        return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor));
    }

                       highestOneBit和lowestOneBit

   /**

     * 1.返回一个 int值,在指定的 int值中最高位(“最左边”)的位置最多只有一个一位。
     * 如果指定值的二进制补码表示中没有一位,即如果它等于零,则返回零
     */
    public static int highestOneBit(int i) {
        // HD, Figure 3-1
        i |= (i >>  1);
        i |= (i >>  2);
        i |= (i >>  4);
        i |= (i >>  8);
        i |= (i >> 16);
        return i - (i >>> 1);
    }

    /**

     * 1.返回一个int值,最多只有一个一位,位于指定的 int值中最低(“最右边”)一位的位置。
     * 如果指定值的二进制补码表示中没有一位,即如果它等于零,则返回零
     */
    public static int lowestOneBit(int i) {
        // HD, Section 2-1
        return i & -i;
    }

               


    /**
     * 1.返回指定int值的二进制补码表示中最高位(“最左边”)一位之前的零位数。
     * 如果指定值在其二进制补码表示中没有一位,换句话说,如果它等于 0,则返回 32。

     * 2.请注意,此方法与以 2 为底的对数密切相关。对于所有正 int值 x:
     *      floor(log2(x)) = 31 - numberOfLeadingZeros(x)
     *      ceil(log2(x)) = 32 - numberOfLeadingZeros(x - 1)

     */
    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;
    }

    /**
     * 返回指定 int值的二进制补码表示中的最低位(“最右边”)一位之后的零位数。
     * 如果指定值在其二进制补码表示中没有一位,换句话说,如果它等于 0,则返回 32。
     */
    public static int numberOfTrailingZeros(int i) {
        // HD, Figure 5-14
        int y;
        if (i == 0) return 32;
        int n = 31;
        y = i <<16; if (y != 0) { n = n -16; i = y; }
        y = i << 8; if (y != 0) { n = n - 8; i = y; }
        y = i << 4; if (y != 0) { n = n - 4; i = y; }
        y = i << 2; if (y != 0) { n = n - 2; i = y; }
        return n - ((i << 1) >>> 31);
    }

    /**
     * 返回指定 int值的二进制补码表示中的一位数。此函数有时称为人口计数。
     */
    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;
    }

    /**
     * 1.返回通过将指定的int值的二进制补码表示形式向左旋转指定位数而获得的值。 
     * (从左手或高阶移出的位重新进入右侧或低阶。)
     * 2.请注意,负距离的左旋转等效于右旋转: rotateLeft(val, -distance) == rotateRight(val, distance)。
     * 另请注意,以 32 的任意倍数旋转是空操作,因此可以忽略旋转距离的最后五位以外的所有位,
     * 即使距离为负数:rotateLeft(val, distance) == rotateLeft( val、距离和 0x1F)。

     */
    public static int rotateLeft(int i, int distance) {
        return (i << distance) | (i >>> -distance);
    }

    /**
     * 1.返回通过将指定的int值的二进制补码表示向右旋转指定的位数而获得的值。 
     * (从右侧移出的位,或低位,在左侧重新进入,或高位。)
     * 2.请注意,负距离的右旋转等同于左旋转:rotateRight(val, -distance) == rotateLeft(val, distance)
     * 。另请注意,以 32 的任意倍数旋转是空操作,因此可以忽略旋转距离的最后五位以外的所有位,
     * 即使距离为负数: rotateRight(val, distance) == rotateRight( val、距离和 0x1F)。
     */
    public static int rotateRight(int i, int distance) {
        return (i >>> distance) | (i << -distance);
    }

    /**
     * 返回通过反转指定 int值的二进制补码表示中的位顺序而获得的值。
     */
    public static int reverse(int i) {
        // HD, Figure 7-1
        i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
        i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
        i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
        i = (i << 24) | ((i & 0xff00) << 8) |
            ((i >>> 8) & 0xff00) | (i >>> 24);
        return i;
    }

    /**
     * 返回指定int值的符号函数。 
     * (如果指定值为负,则返回值为 -1;如果指定值为 0,则返回值为 0;如果指定值为正,则返回值为 1。)
     */
    public static int signum(int i) {
        // HD, Section 2-7
        return (i >> 31) | (-i >>> 31);
    }

    /**
     * 1.返回通过反转指定 int 值的二进制补码表示中的字节顺序而获得的值。
     */
    public static int reverseBytes(int i) {
        return ((i >>> 24)           ) |
               ((i >>   8) &   0xFF00) |
               ((i <<   8) & 0xFF0000) |
               ((i << 24));
    }

        int的比较

    /**
     * 根据 + 运算符将两个整数相加。
     */
    public static int sum(int a, int b) {
        return a + b;
    }

    /**
     * 返回两个int值中的较大者,就像通过调用 Math.max(int, int) 
     */
    public static int max(int a, int b) {
        return Math.max(a, b);
    }

    /**
     * 返回两个int值中较小的一个,就像通过调用 Math.min(int, int)
     */
    public static int min(int a, int b) {
        return Math.min(a, b);
    }

七.总结

        以为基础类型都差不多,果然出意外了,各种补码操作,又上了一课...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值