10 java.lang.Integer

26688 ワード

1️⃣クラス定義
public final class Integer extends Number implements Comparable
  • クラスはfinalと定義され、継承できないことを示す.
  • クラスはNumber抽象クラスを実現し、Numberタイプ間の変換を実現することができる.
  • クラスはComparableインタフェースを実現し、比較することができる.

  • 2️⃣ツールバーの
        /**
         * int           .
         */
        @Native public static final int   MIN_VALUE = 0x80000000;
    
        /**
         * int           .
         */
        @Native public static final int   MAX_VALUE = 0x7fffffff;
    
        /**
         * @SuppressWarnings("unchecked")          
         *   int   class  
         */
        @SuppressWarnings("unchecked")
        public static final Class  TYPE = (Class) 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'
        };
        
        /**
         *        10     
         */
        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',
            } ;
        
        /**
         * 100      10     
         */
        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',
            } ;
        
        /**
         * sizeTable   ,        ,cpu            
         * cache (      ),    sizeTable        。
         */
        final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
                                          99999999, 999999999, Integer.MAX_VALUE };
         
        /**
         *   int   
         */
        static int stringSize(int x) {
            for (int i=0; ; i++)
                if (x <= sizeTable[i])
                    return i+1;
        }
        
        /**
         *  Integer    ,    -128 127         Integer  cache 
         */
        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
                        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 ,  final.
         */
        private final int value;
    
        /**
         *    
         */
        private static final long serialVersionUID = 1360826667806852920L;
    
        /**
         *   int    32 .
         */
        @Native public static final int SIZE = 32;
    
        /**
         *    4    ,     Byte     Byte.SIZE   8
         */
        public static final int BYTES = SIZE / Byte.SIZE;
    

    3️⃣コンストラクタ
        /**
         *    int   value       
         */
        public Integer(int value) {
            this.value = value;
        }
    
        /**
         *  string   int,    parseInt       ;
         */
        public Integer(String s) throws NumberFormatException {
            this.value = parseInt(s, 10);
        }
    

    4️⃣方法
    ① toString()
        /**
         *                
         *           。
         */
        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));
        }
    
        /**
         * toString     
         */
        public static String toString(int i) {
            //  i         Int       ,              
            if (i == Integer.MIN_VALUE)
                return "-2147483648";
            //     i   ,         。   stringSize      
            int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
            //     char     size;
            char[] buf = new char[size];
            //      getChars    ;
            getChars(i, size, buf);
            //   String            ,                  ;
            return new String(buf, true);
        }
        
        /**
         *            toString(int i)      
         */
        public String toString() {
            return toString(value);
        }
    

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

    ③ getChars()
        /**
         *      i         buf .
         */
        static void getChars(int i, int index, char[] buf) {
            int q, r;
            int charPos = index;
            char sign = 0;
    
            if (i < 0) {
                sign = '-';
                i = -i;
            }
    
            //          
            while (i >= 65536) {
                q = i / 100;
                r = i - ((q << 6) + (q << 5) + (q << 2));
                i = q;
                //  DigitOnes[r]        r%10   
                buf [--charPos] = DigitOnes[r];
                //  DigitTens[r]         r/10   
                buf [--charPos] = DigitTens[r];
            }
    
            //                   
            for (;;) {
                q = (i * 52429) >>> (16+3);
                r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
                buf [--charPos] = digits [r];
                i = q;
                if (i == 0) break;
            }
            if (sign != 0) {
                buf [--charPos] = sign;
            }
        }
    

    ④ parseInt()
        /**
         *  String  Integer     ,            ,      NumberFormatException      :
         * 1.        null            。
         * 2.      Character.MIN_RADIX      Character.MAX_RADIX。
         * 3.            1,               ‘-‘ (‘u002D’)  ,                       .
         * 4.          int     。
         */
        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;
        }
        
        /**
         *  String  Integer,       parseInt       
         */
        public static int parseInt(String s) throws NumberFormatException {
            return parseInt(s,10);
        }
    

    ⑤ parseUnsignedInt()
        /**
         *                 ,       parseUnsignedInt        .
         */
        public static int parseUnsignedInt(String s) throws NumberFormatException {
            return parseUnsignedInt(s, 10);
        }
        
        /**
         *                     
         */
        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);
            }
        }
    

    ⑥ valueOf()
        /**
         *          Integer        ,          
         *           -127 128  ,        。         。
         */
        public static Integer valueOf(int i) {
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }
        
        /**
         *      Integer   ,     valueOf(String s, int radix)      
         *        .
         */
        public static Integer valueOf(String s) throws NumberFormatException {
            return Integer.valueOf(parseInt(s, 10));
        }
        
        /**
         *      Integer   。         radix,          
         *                   。               。
         */
        public static Integer valueOf(String s, int radix) throws NumberFormatException {
            return Integer.valueOf(parseInt(s,radix));
        }
    

    ⑦Number継承クラスからのメソッド実装
        /**
         *         byte,   Number  
         */
        public byte byteValue() {
            return (byte)value;
        }
    
        /**
         *         short,   Number  
         */
        public short shortValue() {
            return (short)value;
        }
    
        /**
         *   Integer   int ,   Number  
         */
        public int intValue() {
            return value;
        }
    
        /**
         *         long,   Number  
         */
        public long longValue() {
            return (long)value;
        }
    
        /**
         *         float,   Number  
         */
        public float floatValue() {
            return (float)value;
        }
    
        /**
         *         double,   Number  
         */
        public double doubleValue() {
            return (double)value;
        }
    

    ⑧hashCode()とequals()
        /**
         * hashCode     hashCode  
         */
        @Override
        public int hashCode() {
            return Integer.hashCode(value);
        }
    
        /**
         * hashCode    value
         */
        public static int hashCode(int value) {
            return value;
        }
    
        /**
         *                     
         */
        public boolean equals(Object obj) {
            if (obj instanceof Integer) {
                return value == ((Integer)obj).intValue();
            }
            return false;
        }
    

    ⑨ getInteger()
        /**
         *                  ,       getInteger(String nm, int val)
         *       .
         */
        public static Integer getInteger(String nm) {
            return getInteger(nm, null);
        }
        
        /**
         *                  ,       getInteger(String nm, Integer val)
         *       .
         */
        public static Integer getInteger(String nm, int val) {
            Integer result = getInteger(nm, null);
            return (result == null) ? Integer.valueOf(val) : result;
        }
        
        /**
         *                  。               
         *  。  System.getProperty(java.lang.String)       
         *     。  ,                 ,       
         *   Integer   。   getProperty               
         *        。    nm   System props     。    
         *   getInteger           .
         */
        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;
        }
    

    ⑩その他の方法:最後のいくつかの方法はよく使わないで、分析を経ないで直接翻訳を行った.
        /**
         *             ,     、          .
         */
        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;
        }
        
        ________________________________________________________
        
        /**
         *     int      ,     compare()  
         */
        public int compareTo(Integer anotherInteger) {
            return compare(this.value, anotherInteger.value);
        }
        
        /**
         *   int      ,        
         */
        public static int compare(int x, int y) {
            return (x < y) ? -1 : ((x == y) ? 0 : 1);
        }
        
        ________________________________________________________
        /**
         *        int         ,  compare  
         */
        public static int compareUnsigned(int x, int y) {
            return compare(x + MIN_VALUE, y + MIN_VALUE);
        }
        
        ________________________________________________________
        /**
         *          long
         */
        public static long toUnsignedLong(int x) {
            return ((long) x) & 0xffffffffL;
        }
        
        ________________________________________________________
        /**
         *               (    )
         */
        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));
        }
        
        ________________________________________________________
        /**
         *                      (“  ”)    
         *  int 。      no,   0.
         */
        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);
        }
        
        ________________________________________________________
        /**
         *                      (“  ”)    
         *  int 。      no,   0.
         */
        public static int lowestOneBit(int i) {
            // HD, Section 2-1
            return i & -i;
        }
        
        ________________________________________________________
        /**
         *         0    
         * (“  ”)             
         *   int 。                 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 。      no,   32
         * 1    2       ,    ,     
         *    。
         */
        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;
        }
        
        ________________________________________________________
        /**
         *                  
         *      int ( )
         */
        public static int rotateLeft(int i, int distance) {
            return (i << distance) | (i >>> -distance);
        }
        
        ________________________________________________________
        /**
         *                  
         *      int ( )
         */
        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  sgn  。(
         *        ,    -1;   0
         *      ;       ,  1
         */
        public static int signum(int i) {
            // HD, Section 2-7
            return (i >> 31) | (-i >>> 31);
        }
        
        ________________________________________________________
        /**
         *                
         *   int        。
         */
        public static int reverseBytes(int i) {
            return ((i >>> 24)           ) |
                   ((i >>   8) &   0xFF00) |
                   ((i <<   8) & 0xFF0000) |
                   ((i << 24));
        }
        
        ________________________________________________________
        /**
         *     
         */
        public static int sum(int a, int b) {
            return a + b;
        }
    
        /**
         *     int      ,  Math.max  
         */
        public static int max(int a, int b) {
            return Math.max(a, b);
        }
    
        /**
         *     int      ,  Math.max  
         */
        public static int min(int a, int b) {
            return Math.min(a, b);
        }
    

    5️⃣まとめ
  • このクラスにはpublis static fianlプロパティが大量にあり、使用できるときはできるだけ使用することができ、コードの読みやすさだけでなく、パフォーマンスを向上させ、リソースを節約することができます.
  • Integerオブジェクトを初期化すると、10進数の整数しか作成できません.
  • Integerには、Integerクラスがロードされたときに実行する動的コードブロックがあり、通常はIntegerCacheが決定する.low=-128,IntegerCache.high=127のような値(java.lang.Integer.IntegerCache.highを宣言する値が表示されない限り).
  • int変数をIntegerに変換する場合(またはIntegerを新規作成する場合)、構築関数の代わりにvalueOf法を使用することを推奨します.あるいはInteger i=100を直接使用します.コンパイラはInteger s=Integerに変わります.valueOf(100);
  • StringをIntegerに変換するすべての方法はparseIntメソッドに基づいて実現され、彼らの呼び出しスタックはgetInteger(String nm)--->getInteger(nm,null);--->Integer.decode()--->Integer.valueOf()--->parseInt()
  • parseIntメソッドは基本タイプintを返し、他のメソッドはIntegerを返し、valueOf(String)メソッドはvalueOf(int)メソッドを呼び出す.(オブジェクトを1つ必要とせずに基本タイプを返す必要がある場合は、Integert.parseInt(「123」)を直接使用できます.オブジェクトが必要な場合は、キャッシュによるメリットがあるためvalueOf()を使用することをお勧めします.進数に関係がある場合はdecode法を使います.システム構成から値を取得する場合はgetInteger)
  • を使用します.