导航

java.lang.Integer源码浅析

Posted on 2018-04-05 16:14  水狼渊  阅读(592)  评论(0)    收藏  举报
  1. Integer定义,final不可修改的类
    1 public final class Integer extends Number implements Comparable<Integer>
  2. 常量定义
     1     /**
     2      * A constant holding the minimum value an {@code int} can
     3      * have, -2<sup>31</sup>.
     4      */
     5     @Native public static final int   MIN_VALUE = 0x80000000;
     6 
     7     /**
     8      * A constant holding the maximum value an {@code int} can
     9      * have, 2<sup>31</sup>-1.
    10      */
    11     @Native public static final int   MAX_VALUE = 0x7fffffff;
    12 
    13     /**
    14      * The {@code Class} instance representing the primitive type
    15      * {@code int}.
    16      *
    17      * @since   JDK1.1
    18      */
    19     @SuppressWarnings("unchecked")
    20     public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
    21     
    22     /**
    23      * All possible chars for representing a number as a String
    24      */
    25     final static char[] digits = {
    26         '0' , '1' , '2' , '3' , '4' , '5' ,
    27         '6' , '7' , '8' , '9' , 'a' , 'b' ,
    28         'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
    29         'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
    30         'o' , 'p' , 'q' , 'r' , 's' , 't' ,
    31         'u' , 'v' , 'w' , 'x' , 'y' , 'z'
    32     };
    33 
    34     final static char [] DigitTens = {
    35         '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
    36         '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
    37         '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
    38         '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
    39         '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
    40         '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
    41         '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
    42         '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
    43         '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
    44         '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
    45         } ;
    46 
    47     final static char [] DigitOnes = {
    48         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    49         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    50         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    51         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    52         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    53         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    54         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    55         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    56         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    57         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    58         } ;
    59     
    constant

    int表示的最大值MAX_VALUE,最小值负值MIN_VALUE,TYPE,digits的有效性数组定义。

  3. Integer的toString方法
      1     // 静态toString方法,radix为基数
      2     public static String toString(int i, int radix) {
      3         // 最小为2,最大36,范围外默认10
      4         if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
      5             radix = 10;
      6 
      7         /* Use the faster version */
      8         if (radix == 10) {
      9             // toString 默认为10
     10             return toString(i);
     11         }
     12         
     13         // buf数组为int 目标char。长度33,因为int为8字节32位,多出来的是符号位
     14         char buf[] = new char[33];
     15         boolean negative = (i < 0);
     16         int charPos = 32;
     17 
     18         if (!negative) {
     19             i = -i;
     20         }
     21 
     22         while (i <= -radix) {
     23             buf[charPos--] = digits[-(i % radix)];
     24             i = i / radix;
     25         }
     26         // 将最后一个余数赋值
     27         buf[charPos] = digits[-i];
     28 
     29         if (negative) {
     30             // 负数则需要把符号赋值最前面
     31             buf[--charPos] = '-';
     32         }
     33          
     34         // 使用char 加偏移进行String构建
     35         return new String(buf, charPos, (33 - charPos));
     36     }
     37 
     38     // 当int 无符号时,则可以表示long值,所以需要转long进行toStirng
     39     public static String toUnsignedString(int i, int radix) {
     40         return Long.toUnsignedString(toUnsignedLong(i), radix);
     41     }
     42 
     43     // 十六进制 toString, toUnsignedString0 的第二个参数是偏移量,4则为16进制
     44     public static String toHexString(int i) {
     45         return toUnsignedString0(i, 4);
     46     }
     47 
     48     // Octal 无符号的8进制
     49     public static String toOctalString(int i) {
     50         return toUnsignedString0(i, 3);
     51     }
     52 
     53     // Binary无符号的2进制
     54     public static String toBinaryString(int i) {
     55         return toUnsignedString0(i, 1);
     56     }
     57 
     58     // 私有无符号toString方法
     59     private static String toUnsignedString0(int val, int shift) {
     60         // assert shift > 0 && shift <=5 : "Illegal shift value";
     61        // 计算数值的字节数 
     62        int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
     63         // 定义char 的长度
     64         int chars = Math.max(((mag + (shift - 1)) / shift), 1);
     65         char[] buf = new char[chars];
     66 
     67         formatUnsignedInt(val, shift, buf, 0, chars);
     68 
     69         // Use special constructor which takes over "buf".
     70         return new String(buf, true);
     71     }
     72 
     73     /**
     74      * Format a long (treated as unsigned) into a character buffer.
     75      * @param val the unsigned int to format
     76      * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
     77      * @param buf the character buffer to write to
     78      * @param offset the offset in the destination buffer to start at
     79      * @param len the number of characters to write
     80      * @return the lowest character  location used
     81      */
     82      static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
     83         int charPos = len;
     84         int radix = 1 << shift;
     85         int mask = radix - 1;
     86         do {
     87             buf[offset + --charPos] = Integer.digits[val & mask];
     88             val >>>= shift;
     89         } while (val != 0 && charPos > 0);
     90 
     91         return charPos;
     92     }
     93 
     94     /**
     95      * Returns a {@code String} object representing the
     96      * specified integer. The argument is converted to signed decimal
     97      * representation and returned as a string, exactly as if the
     98      * argument and radix 10 were given as arguments to the {@link
     99      * #toString(int, int)} method.
    100      *
    101      * @param   i   an integer to be converted.
    102      * @return  a string representation of the argument in base&nbsp;10.
    103      */
    104     // 使用10进制进行toString,有-符号。
    105     public static String toString(int i) {
    106         if (i == Integer.MIN_VALUE)
    107             return "-2147483648";
    108         int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
    109         char[] buf = new char[size];
    110         getChars(i, size, buf);
    111         return new String(buf, true);
    112     }
    113 
    114     public static String toUnsignedString(int i) {
    115         // 当int 无符号时,则可以表示long值,所以需要转long进行toStirng
    116         return Long.toString(toUnsignedLong(i));
    117     }
    118 
    119     /**
    120      * Places characters representing the integer i into the
    121      * character array buf. The characters are placed into
    122      * the buffer backwards starting with the least significant
    123      * digit at the specified index (exclusive), and working
    124      * backwards from there.
    125      *
    126      * Will fail if i == Integer.MIN_VALUE
    127      */
    128     static void getChars(int i, int index, char[] buf) {
    129         int q, r;
    130         int charPos = index;
    131         char sign = 0;
    132 
    133         if (i < 0) {
    134             sign = '-';
    135             i = -i;
    136         }
    137         // 两位两位进行转char操作
    138         // Generate two digits per iteration
    139         while (i >= 65536) {
    140             q = i / 100;
    141         // really: r = i - (q * 100);
    142             // * 100 拆解成 二进制运算 
    143             r = i - ((q << 6) + (q << 5) + (q << 2));
    144             i = q;
    145             // 赋值 个位数
    146             buf [--charPos] = DigitOnes[r];
    147             // 赋值十位数
    148             buf [--charPos] = DigitTens[r];
    149         }
    150 
    151         // 处理一个字节的小数值
    152         // Fall thru to fast mode for smaller numbers
    153         // assert(i <= 65536, i);
    154         for (;;) {
    155             q = (i * 52429) >>> (16+3);
    156             r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
    157             buf [--charPos] = digits [r];
    158             i = q;
    159             if (i == 0) break;
    160         }
    161         if (sign != 0) {
    162             buf [--charPos] = sign;
    163         }
    164     }
    165     
    166     // 使用数值对应索引来计算一个数需要多少长度char来表示
    167     final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
    168                                       99999999, 999999999, Integer.MAX_VALUE };
    169 
    170     // Requires positive x
    171     static int stringSize(int x) {
    172         for (int i=0; ; i++)
    173             if (x <= sizeTable[i])
    174                 return i+1;
    175     }
    176 
    177     
    toString
  4. parseInt方法
      1     /**
      2      * Parses the string argument as a signed integer in the radix
      3      * specified by the second argument. The characters in the string
      4      * must all be digits of the specified radix (as determined by
      5      * whether {@link java.lang.Character#digit(char, int)} returns a
      6      * nonnegative value), except that the first character may be an
      7      * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to
      8      * indicate a negative value or an ASCII plus sign {@code '+'}
      9      * ({@code '\u005Cu002B'}) to indicate a positive value. The
     10      * resulting integer value is returned.
     11      *
     12      * <p>An exception of type {@code NumberFormatException} is
     13      * thrown if any of the following situations occurs:
     14      * <ul>
     15      * <li>The first argument is {@code null} or is a string of
     16      * length zero.
     17      *
     18      * <li>The radix is either smaller than
     19      * {@link java.lang.Character#MIN_RADIX} or
     20      * larger than {@link java.lang.Character#MAX_RADIX}.
     21      *
     22      * <li>Any character of the string is not a digit of the specified
     23      * radix, except that the first character may be a minus sign
     24      * {@code '-'} ({@code '\u005Cu002D'}) or plus sign
     25      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
     26      * string is longer than length 1.
     27      *
     28      * <li>The value represented by the string is not a value of type
     29      * {@code int}.
     30      * </ul>
     31      *
     32      * <p>Examples:
     33      * <blockquote><pre>
     34      * parseInt("0", 10) returns 0
     35      * parseInt("473", 10) returns 473
     36      * parseInt("+42", 10) returns 42
     37      * parseInt("-0", 10) returns 0
     38      * parseInt("-FF", 16) returns -255
     39      * parseInt("1100110", 2) returns 102
     40      * parseInt("2147483647", 10) returns 2147483647
     41      * parseInt("-2147483648", 10) returns -2147483648
     42      * parseInt("2147483648", 10) throws a NumberFormatException
     43      * parseInt("99", 8) throws a NumberFormatException
     44      * parseInt("Kona", 10) throws a NumberFormatException
     45      * parseInt("Kona", 27) returns 411787
     46      * </pre></blockquote>
     47      *
     48      * @param      s   the {@code String} containing the integer
     49      *                  representation to be parsed
     50      * @param      radix   the radix to be used while parsing {@code s}.
     51      * @return     the integer represented by the string argument in the
     52      *             specified radix.
     53      * @exception  NumberFormatException if the {@code String}
     54      *             does not contain a parsable {@code int}.
     55      */
     56     public static int parseInt(String s, int radix)
     57                 throws NumberFormatException
     58     {
     59         /*
     60          * WARNING: This method may be invoked early during VM initialization
     61          * before IntegerCache is initialized. Care must be taken to not use
     62          * the valueOf method.
     63          */
     64 
     65         if (s == null) {
     66             throw new NumberFormatException("null");
     67         }
     68 
     69         if (radix < Character.MIN_RADIX) {
     70             throw new NumberFormatException("radix " + radix +
     71                                             " less than Character.MIN_RADIX");
     72         }
     73 
     74         if (radix > Character.MAX_RADIX) {
     75             throw new NumberFormatException("radix " + radix +
     76                                             " greater than Character.MAX_RADIX");
     77         }
     78 
     79         int result = 0;
     80         boolean negative = false;
     81         int i = 0, len = s.length();
     82         int limit = -Integer.MAX_VALUE;
     83         int multmin;
     84         int digit;
     85 
     86         if (len > 0) {
     87             char firstChar = s.charAt(0);
     88             if (firstChar < '0') { // Possible leading "+" or "-"
     89                 if (firstChar == '-') {
     90                     negative = true;
     91                     limit = Integer.MIN_VALUE;
     92                 } else if (firstChar != '+')
     93                     throw NumberFormatException.forInputString(s);
     94 
     95                 if (len == 1) // Cannot have lone "+" or "-"
     96                     throw NumberFormatException.forInputString(s);
     97                 i++;
     98             }
     99             multmin = limit / radix;
    100             while (i < len) {
    101                 // Accumulating negatively avoids surprises near MAX_VALUE
    102                 digit = Character.digit(s.charAt(i++),radix);
    103                 if (digit < 0) {
    104                     throw NumberFormatException.forInputString(s);
    105                 }
    106                 if (result < multmin) {
    107                     throw NumberFormatException.forInputString(s);
    108                 }
    109                 result *= radix;
    110                 if (result < limit + digit) {
    111                     throw NumberFormatException.forInputString(s);
    112                 }
    113                 result -= digit;
    114             }
    115         } else {
    116             throw NumberFormatException.forInputString(s);
    117         }
    118         return negative ? result : -result;
    119     }
    120 
    121     /**
    122      * Parses the string argument as a signed decimal integer. The
    123      * characters in the string must all be decimal digits, except
    124      * that the first character may be an ASCII minus sign {@code '-'}
    125      * ({@code '\u005Cu002D'}) to indicate a negative value or an
    126      * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
    127      * indicate a positive value. The resulting integer value is
    128      * returned, exactly as if the argument and the radix 10 were
    129      * given as arguments to the {@link #parseInt(java.lang.String,
    130      * int)} method.
    131      *
    132      * @param s    a {@code String} containing the {@code int}
    133      *             representation to be parsed
    134      * @return     the integer value represented by the argument in decimal.
    135      * @exception  NumberFormatException  if the string does not contain a
    136      *               parsable integer.
    137      */
    138     public static int parseInt(String s) throws NumberFormatException {
    139         return parseInt(s,10);
    140     }
    141 
    142     /**
    143      * Parses the string argument as an unsigned integer in the radix
    144      * specified by the second argument.  An unsigned integer maps the
    145      * values usually associated with negative numbers to positive
    146      * numbers larger than {@code MAX_VALUE}.
    147      *
    148      * The characters in the string must all be digits of the
    149      * specified radix (as determined by whether {@link
    150      * java.lang.Character#digit(char, int)} returns a nonnegative
    151      * value), except that the first character may be an ASCII plus
    152      * sign {@code '+'} ({@code '\u005Cu002B'}). The resulting
    153      * integer value is returned.
    154      *
    155      * <p>An exception of type {@code NumberFormatException} is
    156      * thrown if any of the following situations occurs:
    157      * <ul>
    158      * <li>The first argument is {@code null} or is a string of
    159      * length zero.
    160      *
    161      * <li>The radix is either smaller than
    162      * {@link java.lang.Character#MIN_RADIX} or
    163      * larger than {@link java.lang.Character#MAX_RADIX}.
    164      *
    165      * <li>Any character of the string is not a digit of the specified
    166      * radix, except that the first character may be a plus sign
    167      * {@code '+'} ({@code '\u005Cu002B'}) provided that the
    168      * string is longer than length 1.
    169      *
    170      * <li>The value represented by the string is larger than the
    171      * largest unsigned {@code int}, 2<sup>32</sup>-1.
    172      *
    173      * </ul>
    174      *
    175      *
    176      * @param      s   the {@code String} containing the unsigned integer
    177      *                  representation to be parsed
    178      * @param      radix   the radix to be used while parsing {@code s}.
    179      * @return     the integer represented by the string argument in the
    180      *             specified radix.
    181      * @throws     NumberFormatException if the {@code String}
    182      *             does not contain a parsable {@code int}.
    183      * @since 1.8
    184      */
    185     public static int parseUnsignedInt(String s, int radix)
    186                 throws NumberFormatException {
    187         if (s == null)  {
    188             throw new NumberFormatException("null");
    189         }
    190 
    191         int len = s.length();
    192         if (len > 0) {
    193             char firstChar = s.charAt(0);
    194             if (firstChar == '-') {
    195                 throw new
    196                     NumberFormatException(String.format("Illegal leading minus sign " +
    197                                                        "on unsigned string %s.", s));
    198             } else {
    199                 if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits
    200                     (radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits
    201                     return parseInt(s, radix);
    202                 } else {
    203                     long ell = Long.parseLong(s, radix);
    204                     if ((ell & 0xffff_ffff_0000_0000L) == 0) {
    205                         return (int) ell;
    206                     } else {
    207                         throw new
    208                             NumberFormatException(String.format("String value %s exceeds " +
    209                                                                 "range of unsigned int.", s));
    210                     }
    211                 }
    212             }
    213         } else {
    214             throw NumberFormatException.forInputString(s);
    215         }
    216     }
    217 
    218     /**
    219      * Parses the string argument as an unsigned decimal integer. The
    220      * characters in the string must all be decimal digits, except
    221      * that the first character may be an an ASCII plus sign {@code
    222      * '+'} ({@code '\u005Cu002B'}). The resulting integer value
    223      * is returned, exactly as if the argument and the radix 10 were
    224      * given as arguments to the {@link
    225      * #parseUnsignedInt(java.lang.String, int)} method.
    226      *
    227      * @param s   a {@code String} containing the unsigned {@code int}
    228      *            representation to be parsed
    229      * @return    the unsigned integer value represented by the argument in decimal.
    230      * @throws    NumberFormatException  if the string does not contain a
    231      *            parsable unsigned integer.
    232      * @since 1.8
    233      */
    234     public static int parseUnsignedInt(String s) throws NumberFormatException {
    235         return parseUnsignedInt(s, 10);
    236     }
    parseInt

    若String为null,会抛出null 异常。要注意的是返回值为int,不是Integer对象。

  5. valueOf方法
     1 /**
     2      * Returns an {@code Integer} object holding the value
     3      * extracted from the specified {@code String} when parsed
     4      * with the radix given by the second argument. The first argument
     5      * is interpreted as representing a signed integer in the radix
     6      * specified by the second argument, exactly as if the arguments
     7      * were given to the {@link #parseInt(java.lang.String, int)}
     8      * method. The result is an {@code Integer} object that
     9      * represents the integer value specified by the string.
    10      *
    11      * <p>In other words, this method returns an {@code Integer}
    12      * object equal to the value of:
    13      *
    14      * <blockquote>
    15      *  {@code new Integer(Integer.parseInt(s, radix))}
    16      * </blockquote>
    17      *
    18      * @param      s   the string to be parsed.
    19      * @param      radix the radix to be used in interpreting {@code s}
    20      * @return     an {@code Integer} object holding the value
    21      *             represented by the string argument in the specified
    22      *             radix.
    23      * @exception NumberFormatException if the {@code String}
    24      *            does not contain a parsable {@code int}.
    25      */
    26     public static Integer valueOf(String s, int radix) throws NumberFormatException {
    27         return Integer.valueOf(parseInt(s,radix));
    28     }
    29 
    30     /**
    31      * Returns an {@code Integer} object holding the
    32      * value of the specified {@code String}. The argument is
    33      * interpreted as representing a signed decimal integer, exactly
    34      * as if the argument were given to the {@link
    35      * #parseInt(java.lang.String)} method. The result is an
    36      * {@code Integer} object that represents the integer value
    37      * specified by the string.
    38      *
    39      * <p>In other words, this method returns an {@code Integer}
    40      * object equal to the value of:
    41      *
    42      * <blockquote>
    43      *  {@code new Integer(Integer.parseInt(s))}
    44      * </blockquote>
    45      *
    46      * @param      s   the string to be parsed.
    47      * @return     an {@code Integer} object holding the value
    48      *             represented by the string argument.
    49      * @exception  NumberFormatException  if the string cannot be parsed
    50      *             as an integer.
    51      */
    52     public static Integer valueOf(String s) throws NumberFormatException {
    53         return Integer.valueOf(parseInt(s, 10));
    54     }
    valueOf

    valueOf默认是10进制有符号转换,原理也是parseInt,但是与parseInt不同的是 返回值为Integer

  6. Integer 的重要定义,IntegerCache 
     1 private static class IntegerCache {
     2         static final int low = -128;
     3         static final int high;
     4         static final Integer cache[];
     5 
     6         static {
     7             // high value may be configured by property
     8             int h = 127;
     9             String integerCacheHighPropValue =
    10                 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
    11             if (integerCacheHighPropValue != null) {
    12                 try {
    13                     int i = parseInt(integerCacheHighPropValue);
    14                     i = Math.max(i, 127);
    15                     // Maximum array size is Integer.MAX_VALUE
    16                     h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
    17                 } catch( NumberFormatException nfe) {
    18                     // If the property cannot be parsed into an int, ignore it.
    19                 }
    20             }
    21             high = h;
    22 
    23             cache = new Integer[(high - low) + 1];
    24             int j = low;
    25             for(int k = 0; k < cache.length; k++)
    26                 cache[k] = new Integer(j++);
    27 
    28             // range [-128, 127] must be interned (JLS7 5.1.7)
    29             assert IntegerCache.high >= 127;
    30         }
    31 
    32         private IntegerCache() {}
    33     }
    34 
    35     /**
    36      * Returns an {@code Integer} instance representing the specified
    37      * {@code int} value.  If a new {@code Integer} instance is not
    38      * required, this method should generally be used in preference to
    39      * the constructor {@link #Integer(int)}, as this method is likely
    40      * to yield significantly better space and time performance by
    41      * caching frequently requested values.
    42      *
    43      * This method will always cache values in the range -128 to 127,
    44      * inclusive, and may cache other values outside of this range.
    45      *
    46      * @param  i an {@code int} value.
    47      * @return an {@code Integer} instance representing {@code i}.
    48      * @since  1.5
    49      */
    50     public static Integer valueOf(int i) {
    51         if (i >= IntegerCache.low && i <= IntegerCache.high)
    52             return IntegerCache.cache[i + (-IntegerCache.low)];
    53         return new Integer(i);
    54     }
    55 
    56     /**
    57      * The value of the {@code Integer}.
    58      *
    59      * @serial
    60      */
    61     private final int value;
    62 
    63     /**
    64      * Constructs a newly allocated {@code Integer} object that
    65      * represents the specified {@code int} value.
    66      *
    67      * @param   value   the value to be represented by the
    68      *                  {@code Integer} object.
    69      */
    70     public Integer(int value) {
    71         this.value = value;
    72     }
    73 
    74     /**
    75      * Constructs a newly allocated {@code Integer} object that
    76      * represents the {@code int} value indicated by the
    77      * {@code String} parameter. The string is converted to an
    78      * {@code int} value in exactly the manner used by the
    79      * {@code parseInt} method for radix 10.
    80      *
    81      * @param      s   the {@code String} to be converted to an
    82      *                 {@code Integer}.
    83      * @exception  NumberFormatException  if the {@code String} does not
    84      *               contain a parsable integer.
    85      * @see        java.lang.Integer#parseInt(java.lang.String, int)
    86      */
    87     public Integer(String s) throws NumberFormatException {
    88         this.value = parseInt(s, 10);
    89     }

    IntegerCache 为Integer的缓冲池,当创建Integer对象时,若大小在-128~127之间,则先在缓冲池返回,若空则新建相应对象返回并进入缓冲池。
    从源码可以看出,最大值127是可以通过jvm启动设置进行修改。
    Integer i = 100; 直接赋值语句是自动装箱,原理就是 Integer.valueOf(int i);

  7. Integer实现
     1 /**
     2      * The value of the {@code Integer}.
     3      *
     4      * @serial
     5      */
     6     private final int value;
     7 
     8     /**
     9      * Constructs a newly allocated {@code Integer} object that
    10      * represents the specified {@code int} value.
    11      *
    12      * @param   value   the value to be represented by the
    13      *                  {@code Integer} object.
    14      */
    15     public Integer(int value) {
    16         this.value = value;
    17     }
    18 
    19     /**
    20      * Constructs a newly allocated {@code Integer} object that
    21      * represents the {@code int} value indicated by the
    22      * {@code String} parameter. The string is converted to an
    23      * {@code int} value in exactly the manner used by the
    24      * {@code parseInt} method for radix 10.
    25      *
    26      * @param      s   the {@code String} to be converted to an
    27      *                 {@code Integer}.
    28      * @exception  NumberFormatException  if the {@code String} does not
    29      *               contain a parsable integer.
    30      * @see        java.lang.Integer#parseInt(java.lang.String, int)
    31      */
    32     public Integer(String s) throws NumberFormatException {
    33         this.value = parseInt(s, 10);
    34     }

    value为final int,Integer 对象一旦创建不可改变。

  8. 转化int方法
     1 /**
     2      * Returns the value of this {@code Integer} as a {@code byte}
     3      * after a narrowing primitive conversion.
     4      * @jls 5.1.3 Narrowing Primitive Conversions
     5      */
     6     public byte byteValue() {
     7         return (byte)value;
     8     }
     9 
    10     /**
    11      * Returns the value of this {@code Integer} as a {@code short}
    12      * after a narrowing primitive conversion.
    13      * @jls 5.1.3 Narrowing Primitive Conversions
    14      */
    15     public short shortValue() {
    16         return (short)value;
    17     }
    18 
    19     /**
    20      * Returns the value of this {@code Integer} as an
    21      * {@code int}.
    22      */
    23     public int intValue() {
    24         return value;
    25     }
    26 
    27     /**
    28      * Returns the value of this {@code Integer} as a {@code long}
    29      * after a widening primitive conversion.
    30      * @jls 5.1.2 Widening Primitive Conversions
    31      * @see Integer#toUnsignedLong(int)
    32      */
    33     public long longValue() {
    34         return (long)value;
    35     }
    36 
    37     /**
    38      * Returns the value of this {@code Integer} as a {@code float}
    39      * after a widening primitive conversion.
    40      * @jls 5.1.2 Widening Primitive Conversions
    41      */
    42     public float floatValue() {
    43         return (float)value;
    44     }
    45 
    46     /**
    47      * Returns the value of this {@code Integer} as a {@code double}
    48      * after a widening primitive conversion.
    49      * @jls 5.1.2 Widening Primitive Conversions
    50      */
    51     public double doubleValue() {
    52         return (double)value;
    53     }
    usually
  9. 重写equals , hashcode,toString
     1 /**
     2      * Returns a {@code String} object representing this
     3      * {@code Integer}'s value. The value is converted to signed
     4      * decimal representation and returned as a string, exactly as if
     5      * the integer value were given as an argument to the {@link
     6      * java.lang.Integer#toString(int)} method.
     7      *
     8      * @return  a string representation of the value of this object in
     9      *          base&nbsp;10.
    10      */
    11     public String toString() {
    12         return toString(value);
    13     }
    14 
    15     /**
    16      * Returns a hash code for this {@code Integer}.
    17      *
    18      * @return  a hash code value for this object, equal to the
    19      *          primitive {@code int} value represented by this
    20      *          {@code Integer} object.
    21      */
    22     @Override
    23     public int hashCode() {
    24         return Integer.hashCode(value);
    25     }
    26 
    27     /**
    28      * Returns a hash code for a {@code int} value; compatible with
    29      * {@code Integer.hashCode()}.
    30      *
    31      * @param value the value to hash
    32      * @since 1.8
    33      *
    34      * @return a hash code value for a {@code int} value.
    35      */
    36     public static int hashCode(int value) {
    37         return value;
    38     }
    39 
    40     /**
    41      * Compares this object to the specified object.  The result is
    42      * {@code true} if and only if the argument is not
    43      * {@code null} and is an {@code Integer} object that
    44      * contains the same {@code int} value as this object.
    45      *
    46      * @param   obj   the object to compare with.
    47      * @return  {@code true} if the objects are the same;
    48      *          {@code false} otherwise.
    49      */
    50     public boolean equals(Object obj) {
    51         if (obj instanceof Integer) {
    52             return value == ((Integer)obj).intValue();
    53         }
    54         return false;
    55     }
    revide
  10. 获取系统properties Integer
     1 /**
     2      * Determines the integer value of the system property with the
     3      * specified name.
     4      *
     5      * <p>The first argument is treated as the name of a system
     6      * property.  System properties are accessible through the {@link
     7      * java.lang.System#getProperty(java.lang.String)} method. The
     8      * string value of this property is then interpreted as an integer
     9      * value using the grammar supported by {@link Integer#decode decode} and
    10      * an {@code Integer} object representing this value is returned.
    11      *
    12      * <p>The second argument is the default value. An {@code Integer} object
    13      * that represents the value of the second argument is returned if there
    14      * is no property of the specified name, if the property does not have
    15      * the correct numeric format, or if the specified name is empty or
    16      * {@code null}.
    17      *
    18      * <p>In other words, this method returns an {@code Integer} object
    19      * equal to the value of:
    20      *
    21      * <blockquote>
    22      *  {@code getInteger(nm, new Integer(val))}
    23      * </blockquote>
    24      *
    25      * but in practice it may be implemented in a manner such as:
    26      *
    27      * <blockquote><pre>
    28      * Integer result = getInteger(nm, null);
    29      * return (result == null) ? new Integer(val) : result;
    30      * </pre></blockquote>
    31      *
    32      * to avoid the unnecessary allocation of an {@code Integer}
    33      * object when the default value is not needed.
    34      *
    35      * @param   nm   property name.
    36      * @param   val   default value.
    37      * @return  the {@code Integer} value of the property.
    38      * @throws  SecurityException for the same reasons as
    39      *          {@link System#getProperty(String) System.getProperty}
    40      * @see     java.lang.System#getProperty(java.lang.String)
    41      * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
    42      */
    43     public static Integer getInteger(String nm, int val) {
    44         Integer result = getInteger(nm, null);
    45         return (result == null) ? Integer.valueOf(val) : result;
    46     }
    47 
    48     /**
    49      * Returns the integer value of the system property with the
    50      * specified name.  The first argument is treated as the name of a
    51      * system property.  System properties are accessible through the
    52      * {@link java.lang.System#getProperty(java.lang.String)} method.
    53      * The string value of this property is then interpreted as an
    54      * integer value, as per the {@link Integer#decode decode} method,
    55      * and an {@code Integer} object representing this value is
    56      * returned; in summary:
    57      *
    58      * <ul><li>If the property value begins with the two ASCII characters
    59      *         {@code 0x} or the ASCII character {@code #}, not
    60      *      followed by a minus sign, then the rest of it is parsed as a
    61      *      hexadecimal integer exactly as by the method
    62      *      {@link #valueOf(java.lang.String, int)} with radix 16.
    63      * <li>If the property value begins with the ASCII character
    64      *     {@code 0} followed by another character, it is parsed as an
    65      *     octal integer exactly as by the method
    66      *     {@link #valueOf(java.lang.String, int)} with radix 8.
    67      * <li>Otherwise, the property value is parsed as a decimal integer
    68      * exactly as by the method {@link #valueOf(java.lang.String, int)}
    69      * with radix 10.
    70      * </ul>
    71      *
    72      * <p>The second argument is the default value. The default value is
    73      * returned if there is no property of the specified name, if the
    74      * property does not have the correct numeric format, or if the
    75      * specified name is empty or {@code null}.
    76      *
    77      * @param   nm   property name.
    78      * @param   val   default value.
    79      * @return  the {@code Integer} value of the property.
    80      * @throws  SecurityException for the same reasons as
    81      *          {@link System#getProperty(String) System.getProperty}
    82      * @see     System#getProperty(java.lang.String)
    83      * @see     System#getProperty(java.lang.String, java.lang.String)
    84      */
    85     public static Integer getInteger(String nm, Integer val) {
    86         String v = null;
    87         try {
    88             v = System.getProperty(nm);
    89         } catch (IllegalArgumentException | NullPointerException e) {
    90         }
    91         if (v != null) {
    92             try {
    93                 return Integer.decode(v);
    94             } catch (NumberFormatException e) {
    95             }
    96         }
    97         return val;
    98     }
    getProperty
  11.  decode,解析String的数值(二进制|八进制|十进制|十六进制)
     1 /**
     2      * Decodes a {@code String} into an {@code Integer}.
     3      * Accepts decimal, hexadecimal, and octal numbers given
     4      * by the following grammar:
     5      *
     6      * <blockquote>
     7      * <dl>
     8      * <dt><i>DecodableString:</i>
     9      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
    10      * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
    11      * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
    12      * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
    13      * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
    14      *
    15      * <dt><i>Sign:</i>
    16      * <dd>{@code -}
    17      * <dd>{@code +}
    18      * </dl>
    19      * </blockquote>
    20      *
    21      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
    22      * are as defined in section 3.10.1 of
    23      * <cite>The Java&trade; Language Specification</cite>,
    24      * except that underscores are not accepted between digits.
    25      *
    26      * <p>The sequence of characters following an optional
    27      * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
    28      * "{@code #}", or leading zero) is parsed as by the {@code
    29      * Integer.parseInt} method with the indicated radix (10, 16, or
    30      * 8).  This sequence of characters must represent a positive
    31      * value or a {@link NumberFormatException} will be thrown.  The
    32      * result is negated if first character of the specified {@code
    33      * String} is the minus sign.  No whitespace characters are
    34      * permitted in the {@code String}.
    35      *
    36      * @param     nm the {@code String} to decode.
    37      * @return    an {@code Integer} object holding the {@code int}
    38      *             value represented by {@code nm}
    39      * @exception NumberFormatException  if the {@code String} does not
    40      *            contain a parsable integer.
    41      * @see java.lang.Integer#parseInt(java.lang.String, int)
    42      */
    43     public static Integer decode(String nm) throws NumberFormatException {
    44         int radix = 10;
    45         int index = 0;
    46         boolean negative = false;
    47         Integer result;
    48 
    49         if (nm.length() == 0)
    50             throw new NumberFormatException("Zero length string");
    51         char firstChar = nm.charAt(0);
    52         // Handle sign, if present
    53         if (firstChar == '-') {
    54             negative = true;
    55             index++;
    56         } else if (firstChar == '+')
    57             index++;
    58 
    59         // Handle radix specifier, if present
    60         if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
    61             index += 2;
    62             radix = 16;
    63         }
    64         else if (nm.startsWith("#", index)) {
    65             index ++;
    66             radix = 16;
    67         }
    68         else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
    69             index ++;
    70             radix = 8;
    71         }
    72 
    73         if (nm.startsWith("-", index) || nm.startsWith("+", index))
    74             throw new NumberFormatException("Sign character in wrong position");
    75 
    76         try {
    77             result = Integer.valueOf(nm.substring(index), radix);
    78             result = negative ? Integer.valueOf(-result.intValue()) : result;
    79         } catch (NumberFormatException e) {
    80             // If number is Integer.MIN_VALUE, we'll end up here. The next line
    81             // handles this case, and causes any genuine format error to be
    82             // rethrown.
    83             String constant = negative ? ("-" + nm.substring(index))
    84                                        : nm.substring(index);
    85             result = Integer.valueOf(constant, radix);
    86         }
    87         return result;
    88     }
  12. compareTo 方法,比较一定用 value,或者int值来进行大小比较
     1 /**
     2      * Compares two {@code Integer} objects numerically.
     3      *
     4      * @param   anotherInteger   the {@code Integer} to be compared.
     5      * @return  the value {@code 0} if this {@code Integer} is
     6      *          equal to the argument {@code Integer}; a value less than
     7      *          {@code 0} if this {@code Integer} is numerically less
     8      *          than the argument {@code Integer}; and a value greater
     9      *          than {@code 0} if this {@code Integer} is numerically
    10      *           greater than the argument {@code Integer} (signed
    11      *           comparison).
    12      * @since   1.2
    13      */
    14     public int compareTo(Integer anotherInteger) {
    15         return compare(this.value, anotherInteger.value);
    16     }
    17 
    18     /**
    19      * Compares two {@code int} values numerically.
    20      * The value returned is identical to what would be returned by:
    21      * <pre>
    22      *    Integer.valueOf(x).compareTo(Integer.valueOf(y))
    23      * </pre>
    24      *
    25      * @param  x the first {@code int} to compare
    26      * @param  y the second {@code int} to compare
    27      * @return the value {@code 0} if {@code x == y};
    28      *         a value less than {@code 0} if {@code x < y}; and
    29      *         a value greater than {@code 0} if {@code x > y}
    30      * @since 1.7
    31      */
    32     public static int compare(int x, int y) {
    33         return (x < y) ? -1 : ((x == y) ? 0 : 1);
    34     }
    35 
    36     /**
    37      * Compares two {@code int} values numerically treating the values
    38      * as unsigned.
    39      *
    40      * @param  x the first {@code int} to compare
    41      * @param  y the second {@code int} to compare
    42      * @return the value {@code 0} if {@code x == y}; a value less
    43      *         than {@code 0} if {@code x < y} as unsigned values; and
    44      *         a value greater than {@code 0} if {@code x > y} as
    45      *         unsigned values
    46      * @since 1.8
    47      */
    48     public static int compareUnsigned(int x, int y) {
    49         return compare(x + MIN_VALUE, y + MIN_VALUE);
    50     }
    CompareTO
  13. Integer内置运算方法
      1     /**
      2      * Converts the argument to a {@code long} by an unsigned
      3      * conversion.  In an unsigned conversion to a {@code long}, the
      4      * high-order 32 bits of the {@code long} are zero and the
      5      * low-order 32 bits are equal to the bits of the integer
      6      * argument.
      7      *
      8      * Consequently, zero and positive {@code int} values are mapped
      9      * to a numerically equal {@code long} value and negative {@code
     10      * int} values are mapped to a {@code long} value equal to the
     11      * input plus 2<sup>32</sup>.
     12      *
     13      * @param  x the value to convert to an unsigned {@code long}
     14      * @return the argument converted to {@code long} by an unsigned
     15      *         conversion
     16      * @since 1.8
     17      */
     18     public static long toUnsignedLong(int x) {
     19         return ((long) x) & 0xffffffffL;
     20     }
     21 
     22     /**
     23      * Returns the unsigned quotient of dividing the first argument by
     24      * the second where each argument and the result is interpreted as
     25      * an unsigned value.
     26      *
     27      * <p>Note that in two's complement arithmetic, the three other
     28      * basic arithmetic operations of add, subtract, and multiply are
     29      * bit-wise identical if the two operands are regarded as both
     30      * being signed or both being unsigned.  Therefore separate {@code
     31      * addUnsigned}, etc. methods are not provided.
     32      *
     33      * @param dividend the value to be divided
     34      * @param divisor the value doing the dividing
     35      * @return the unsigned quotient of the first argument divided by
     36      * the second argument
     37      * @see #remainderUnsigned
     38      * @since 1.8
     39      */
     40     public static int divideUnsigned(int dividend, int divisor) {
     41         // In lieu of tricky code, for now just use long arithmetic.
     42         return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor));
     43     }
     44 
     45     /**
     46      * Returns the unsigned remainder from dividing the first argument
     47      * by the second where each argument and the result is interpreted
     48      * as an unsigned value.
     49      *
     50      * @param dividend the value to be divided
     51      * @param divisor the value doing the dividing
     52      * @return the unsigned remainder of the first argument divided by
     53      * the second argument
     54      * @see #divideUnsigned
     55      * @since 1.8
     56      */
     57     public static int remainderUnsigned(int dividend, int divisor) {
     58         // In lieu of tricky code, for now just use long arithmetic.
     59         return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor));
     60     }
     61 
     62     /**
     63       * Adds two integers together as per the + operator.
     64      *
     65      * @param a the first operand
     66      * @param b the second operand
     67      * @return the sum of {@code a} and {@code b}
     68      * @see java.util.function.BinaryOperator
     69      * @since 1.8
     70      */
     71     public static int sum(int a, int b) {
     72         return a + b;
     73     }
     74 
     75     /**
     76      * Returns the greater of two {@code int} values
     77      * as if by calling {@link Math#max(int, int) Math.max}.
     78      *
     79      * @param a the first operand
     80      * @param b the second operand
     81      * @return the greater of {@code a} and {@code b}
     82      * @see java.util.function.BinaryOperator
     83      * @since 1.8
     84      */
     85     public static int max(int a, int b) {
     86         return Math.max(a, b);
     87     }
     88 
     89     /**
     90      * Returns the smaller of two {@code int} values
     91      * as if by calling {@link Math#min(int, int) Math.min}.
     92      *
     93      * @param a the first operand
     94      * @param b the second operand
     95      * @return the smaller of {@code a} and {@code b}
     96      * @see java.util.function.BinaryOperator
     97      * @since 1.8
     98      */
     99     public static int min(int a, int b) {
    100         return Math.min(a, b);
    101     }
    calulator
  14. Integer  位相关方法
      1 /**
      2      * The number of bits used to represent an {@code int} value in two's
      3      * complement binary form.
      4      *
      5      * @since 1.5
      6      */
      7     @Native public static final int SIZE = 32;
      8 
      9     /**
     10      * The number of bytes used to represent a {@code int} value in two's
     11      * complement binary form.
     12      *
     13      * @since 1.8
     14      */
     15     public static final int BYTES = SIZE / Byte.SIZE;
     16 
     17     /**
     18      * Returns an {@code int} value with at most a single one-bit, in the
     19      * position of the highest-order ("leftmost") one-bit in the specified
     20      * {@code int} value.  Returns zero if the specified value has no
     21      * one-bits in its two's complement binary representation, that is, if it
     22      * is equal to zero.
     23      *
     24      * @param i the value whose highest one bit is to be computed
     25      * @return an {@code int} value with a single one-bit, in the position
     26      *     of the highest-order one-bit in the specified value, or zero if
     27      *     the specified value is itself equal to zero.
     28      * @since 1.5
     29      */
     30     public static int highestOneBit(int i) {
     31         // HD, Figure 3-1
     32         i |= (i >>  1);
     33         i |= (i >>  2);
     34         i |= (i >>  4);
     35         i |= (i >>  8);
     36         i |= (i >> 16);
     37         return i - (i >>> 1);
     38     }
     39 
     40     /**
     41      * Returns an {@code int} value with at most a single one-bit, in the
     42      * position of the lowest-order ("rightmost") one-bit in the specified
     43      * {@code int} value.  Returns zero if the specified value has no
     44      * one-bits in its two's complement binary representation, that is, if it
     45      * is equal to zero.
     46      *
     47      * @param i the value whose lowest one bit is to be computed
     48      * @return an {@code int} value with a single one-bit, in the position
     49      *     of the lowest-order one-bit in the specified value, or zero if
     50      *     the specified value is itself equal to zero.
     51      * @since 1.5
     52      */
     53     public static int lowestOneBit(int i) {
     54         // HD, Section 2-1
     55         return i & -i;
     56     }
     57 
     58     /**
     59      * Returns the number of zero bits preceding the highest-order
     60      * ("leftmost") one-bit in the two's complement binary representation
     61      * of the specified {@code int} value.  Returns 32 if the
     62      * specified value has no one-bits in its two's complement representation,
     63      * in other words if it is equal to zero.
     64      *
     65      * <p>Note that this method is closely related to the logarithm base 2.
     66      * For all positive {@code int} values x:
     67      * <ul>
     68      * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}
     69      * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}
     70      * </ul>
     71      *
     72      * @param i the value whose number of leading zeros is to be computed
     73      * @return the number of zero bits preceding the highest-order
     74      *     ("leftmost") one-bit in the two's complement binary representation
     75      *     of the specified {@code int} value, or 32 if the value
     76      *     is equal to zero.
     77      * @since 1.5
     78      */
     79     public static int numberOfLeadingZeros(int i) {
     80         // HD, Figure 5-6
     81         if (i == 0)
     82             return 32;
     83         int n = 1;
     84         if (i >>> 16 == 0) { n += 16; i <<= 16; }
     85         if (i >>> 24 == 0) { n +=  8; i <<=  8; }
     86         if (i >>> 28 == 0) { n +=  4; i <<=  4; }
     87         if (i >>> 30 == 0) { n +=  2; i <<=  2; }
     88         n -= i >>> 31;
     89         return n;
     90     }
     91 
     92     /**
     93      * Returns the number of zero bits following the lowest-order ("rightmost")
     94      * one-bit in the two's complement binary representation of the specified
     95      * {@code int} value.  Returns 32 if the specified value has no
     96      * one-bits in its two's complement representation, in other words if it is
     97      * equal to zero.
     98      *
     99      * @param i the value whose number of trailing zeros is to be computed
    100      * @return the number of zero bits following the lowest-order ("rightmost")
    101      *     one-bit in the two's complement binary representation of the
    102      *     specified {@code int} value, or 32 if the value is equal
    103      *     to zero.
    104      * @since 1.5
    105      */
    106     public static int numberOfTrailingZeros(int i) {
    107         // HD, Figure 5-14
    108         int y;
    109         if (i == 0) return 32;
    110         int n = 31;
    111         y = i <<16; if (y != 0) { n = n -16; i = y; }
    112         y = i << 8; if (y != 0) { n = n - 8; i = y; }
    113         y = i << 4; if (y != 0) { n = n - 4; i = y; }
    114         y = i << 2; if (y != 0) { n = n - 2; i = y; }
    115         return n - ((i << 1) >>> 31);
    116     }
    117 
    118     /**
    119      * Returns the number of one-bits in the two's complement binary
    120      * representation of the specified {@code int} value.  This function is
    121      * sometimes referred to as the <i>population count</i>.
    122      *
    123      * @param i the value whose bits are to be counted
    124      * @return the number of one-bits in the two's complement binary
    125      *     representation of the specified {@code int} value.
    126      * @since 1.5
    127      */
    128     public static int bitCount(int i) {
    129         // HD, Figure 5-2
    130         i = i - ((i >>> 1) & 0x55555555);
    131         i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
    132         i = (i + (i >>> 4)) & 0x0f0f0f0f;
    133         i = i + (i >>> 8);
    134         i = i + (i >>> 16);
    135         return i & 0x3f;
    136     }
    137 
    138     /**
    139      * Returns the value obtained by rotating the two's complement binary
    140      * representation of the specified {@code int} value left by the
    141      * specified number of bits.  (Bits shifted out of the left hand, or
    142      * high-order, side reenter on the right, or low-order.)
    143      *
    144      * <p>Note that left rotation with a negative distance is equivalent to
    145      * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
    146      * distance)}.  Note also that rotation by any multiple of 32 is a
    147      * no-op, so all but the last five bits of the rotation distance can be
    148      * ignored, even if the distance is negative: {@code rotateLeft(val,
    149      * distance) == rotateLeft(val, distance & 0x1F)}.
    150      *
    151      * @param i the value whose bits are to be rotated left
    152      * @param distance the number of bit positions to rotate left
    153      * @return the value obtained by rotating the two's complement binary
    154      *     representation of the specified {@code int} value left by the
    155      *     specified number of bits.
    156      * @since 1.5
    157      */
    158     public static int rotateLeft(int i, int distance) {
    159         return (i << distance) | (i >>> -distance);
    160     }
    161 
    162     /**
    163      * Returns the value obtained by rotating the two's complement binary
    164      * representation of the specified {@code int} value right by the
    165      * specified number of bits.  (Bits shifted out of the right hand, or
    166      * low-order, side reenter on the left, or high-order.)
    167      *
    168      * <p>Note that right rotation with a negative distance is equivalent to
    169      * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
    170      * distance)}.  Note also that rotation by any multiple of 32 is a
    171      * no-op, so all but the last five bits of the rotation distance can be
    172      * ignored, even if the distance is negative: {@code rotateRight(val,
    173      * distance) == rotateRight(val, distance & 0x1F)}.
    174      *
    175      * @param i the value whose bits are to be rotated right
    176      * @param distance the number of bit positions to rotate right
    177      * @return the value obtained by rotating the two's complement binary
    178      *     representation of the specified {@code int} value right by the
    179      *     specified number of bits.
    180      * @since 1.5
    181      */
    182     public static int rotateRight(int i, int distance) {
    183         return (i >>> distance) | (i << -distance);
    184     }
    185 
    186     /**
    187      * Returns the value obtained by reversing the order of the bits in the
    188      * two's complement binary representation of the specified {@code int}
    189      * value.
    190      *
    191      * @param i the value to be reversed
    192      * @return the value obtained by reversing order of the bits in the
    193      *     specified {@code int} value.
    194      * @since 1.5
    195      */
    196     public static int reverse(int i) {
    197         // HD, Figure 7-1
    198         i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
    199         i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
    200         i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
    201         i = (i << 24) | ((i & 0xff00) << 8) |
    202             ((i >>> 8) & 0xff00) | (i >>> 24);
    203         return i;
    204     }
    205 
    206     /**
    207      * Returns the signum function of the specified {@code int} value.  (The
    208      * return value is -1 if the specified value is negative; 0 if the
    209      * specified value is zero; and 1 if the specified value is positive.)
    210      *
    211      * @param i the value whose signum is to be computed
    212      * @return the signum function of the specified {@code int} value.
    213      * @since 1.5
    214      */
    215     public static int signum(int i) {
    216         // HD, Section 2-7
    217         return (i >> 31) | (-i >>> 31);
    218     }
    219 
    220     /**
    221      * Returns the value obtained by reversing the order of the bytes in the
    222      * two's complement representation of the specified {@code int} value.
    223      *
    224      * @param i the value whose bytes are to be reversed
    225      * @return the value obtained by reversing the bytes in the specified
    226      *     {@code int} value.
    227      * @since 1.5
    228      */
    229     public static int reverseBytes(int i) {
    230         return ((i >>> 24)           ) |
    231                ((i >>   8) &   0xFF00) |
    232                ((i <<   8) & 0xFF0000) |
    233                ((i << 24));
    234     }
    Bit twiddling
  15. 序列化
    1 /** use serialVersionUID from JDK 1.0.2 for interoperability */
    2     @Native private static final long serialVersionUID = 1360826667806852920L;