Source Code Cross Referenced for Integer.java in  » 6.0-JDK-Core » lang » java » lang » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Home
Java Source Code / Java Documentation
1.6.0 JDK Core
2.6.0 JDK Modules
3.6.0 JDK Modules com.sun
4.6.0 JDK Modules com.sun.java
5.6.0 JDK Modules sun
6.6.0 JDK Platform
7.Ajax
8.Apache Harmony Java SE
9.Aspect oriented
10.Authentication Authorization
11.Blogger System
12.Build
13.Byte Code
14.Cache
15.Chart
16.Chat
17.Code Analyzer
18.Collaboration
19.Content Management System
20.Database Client
21.Database DBMS
22.Database JDBC Connection Pool
23.Database ORM
24.Development
25.EJB Server
26.ERP CRM Financial
27.ESB
28.Forum
29.Game
30.GIS
31.Graphic 3D
32.Graphic Library
33.Groupware
34.HTML Parser
35.IDE
36.IDE Eclipse
37.IDE Netbeans
38.Installer
39.Internationalization Localization
40.Inversion of Control
41.Issue Tracking
42.J2EE
43.J2ME
44.JBoss
45.JMS
46.JMX
47.Library
48.Mail Clients
49.Music
50.Net
51.Parser
52.PDF
53.Portal
54.Profiler
55.Project Management
56.Report
57.RSS RDF
58.Rule Engine
59.Science
60.Scripting
61.Search Engine
62.Security
63.Sevlet Container
64.Source Control
65.Swing Library
66.Template Engine
67.Test Coverage
68.Testing
69.UML
70.Web Crawler
71.Web Framework
72.Web Mail
73.Web Server
74.Web Services
75.Web Services apache cxf 2.2.6
76.Web Services AXIS2
77.Wiki Engine
78.Workflow Engines
79.XML
80.XML UI
Java Source Code / Java Documentation » 6.0 JDK Core » lang » java.lang 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001        /*
0002         * Copyright 1994-2006 Sun Microsystems, Inc.  All Rights Reserved.
0003         * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0004         *
0005         * This code is free software; you can redistribute it and/or modify it
0006         * under the terms of the GNU General Public License version 2 only, as
0007         * published by the Free Software Foundation.  Sun designates this
0008         * particular file as subject to the "Classpath" exception as provided
0009         * by Sun in the LICENSE file that accompanied this code.
0010         *
0011         * This code is distributed in the hope that it will be useful, but WITHOUT
0012         * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0013         * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
0014         * version 2 for more details (a copy is included in the LICENSE file that
0015         * accompanied this code).
0016         *
0017         * You should have received a copy of the GNU General Public License version
0018         * 2 along with this work; if not, write to the Free Software Foundation,
0019         * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0020         *
0021         * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
0022         * CA 95054 USA or visit www.sun.com if you need additional information or
0023         * have any questions.
0024         */
0025
0026        package java.lang;
0027
0028        /**
0029         * The {@code Integer} class wraps a value of the primitive type
0030         * {@code int} in an object. An object of type {@code Integer}
0031         * contains a single field whose type is {@code int}.
0032         *
0033         * <p>In addition, this class provides several methods for converting
0034         * an {@code int} to a {@code String} and a {@code String} to an
0035         * {@code int}, as well as other constants and methods useful when
0036         * dealing with an {@code int}.
0037         *
0038         * <p>Implementation note: The implementations of the "bit twiddling"
0039         * methods (such as {@link #highestOneBit(int) highestOneBit} and
0040         * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are
0041         * based on material from Henry S. Warren, Jr.'s <i>Hacker's
0042         * Delight</i>, (Addison Wesley, 2002).
0043         *
0044         * @author  Lee Boynton
0045         * @author  Arthur van Hoff
0046         * @author  Josh Bloch
0047         * @author  Joseph D. Darcy
0048         * @version 1.102, 07/12/07
0049         * @since JDK1.0
0050         */
0051        public final class Integer extends Number implements 
0052                Comparable<Integer> {
0053            /**
0054             * A constant holding the minimum value an {@code int} can
0055             * have, -2<sup>31</sup>.
0056             */
0057            public static final int MIN_VALUE = 0x80000000;
0058
0059            /**
0060             * A constant holding the maximum value an {@code int} can
0061             * have, 2<sup>31</sup>-1.
0062             */
0063            public static final int MAX_VALUE = 0x7fffffff;
0064
0065            /**
0066             * The {@code Class} instance representing the primitive type
0067             * {@code int}.
0068             *
0069             * @since   JDK1.1
0070             */
0071            public static final Class<Integer> TYPE = (Class<Integer>) Class
0072                    .getPrimitiveClass("int");
0073
0074            /**
0075             * All possible chars for representing a number as a String
0076             */
0077            final static char[] digits = { '0', '1', '2', '3', '4', '5', '6',
0078                    '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
0079                    'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
0080                    'v', 'w', 'x', 'y', 'z' };
0081
0082            /**
0083             * Returns a string representation of the first argument in the
0084             * radix specified by the second argument.
0085             * 
0086             * <p>If the radix is smaller than {@code Character.MIN_RADIX}
0087             * or larger than {@code Character.MAX_RADIX}, then the radix
0088             * {@code 10} is used instead.
0089             * 
0090             * <p>If the first argument is negative, the first element of the
0091             * result is the ASCII minus character {@code '-'}
0092             * (<code>'&#92;u002D'</code>). If the first argument is not
0093             * negative, no sign character appears in the result.
0094             * 
0095             * <p>The remaining characters of the result represent the magnitude
0096             * of the first argument. If the magnitude is zero, it is
0097             * represented by a single zero character {@code '0'}
0098             * (<code>'&#92;u0030'</code>); otherwise, the first character of
0099             * the representation of the magnitude will not be the zero
0100             * character.  The following ASCII characters are used as digits: 
0101             *
0102             * <blockquote>
0103             *   {@code 0123456789abcdefghijklmnopqrstuvwxyz}
0104             * </blockquote>
0105             *
0106             * These are <code>'&#92;u0030'</code> through
0107             * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through
0108             * <code>'&#92;u007A'</code>. If {@code radix} is
0109             * <var>N</var>, then the first <var>N</var> of these characters
0110             * are used as radix-<var>N</var> digits in the order shown. Thus,
0111             * the digits for hexadecimal (radix 16) are
0112             * {@code 0123456789abcdef}. If uppercase letters are
0113             * desired, the {@link java.lang.String#toUpperCase()} method may
0114             * be called on the result:
0115             *
0116             * <blockquote>
0117             *  {@code Integer.toString(n, 16).toUpperCase()}
0118             * </blockquote>
0119             *
0120             * @param   i       an integer to be converted to a string.
0121             * @param   radix   the radix to use in the string representation.
0122             * @return  a string representation of the argument in the specified radix.
0123             * @see     java.lang.Character#MAX_RADIX
0124             * @see     java.lang.Character#MIN_RADIX
0125             */
0126            public static String toString(int i, int radix) {
0127
0128                if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
0129                    radix = 10;
0130
0131                /* Use the faster version */
0132                if (radix == 10) {
0133                    return toString(i);
0134                }
0135
0136                char buf[] = new char[33];
0137                boolean negative = (i < 0);
0138                int charPos = 32;
0139
0140                if (!negative) {
0141                    i = -i;
0142                }
0143
0144                while (i <= -radix) {
0145                    buf[charPos--] = digits[-(i % radix)];
0146                    i = i / radix;
0147                }
0148                buf[charPos] = digits[-i];
0149
0150                if (negative) {
0151                    buf[--charPos] = '-';
0152                }
0153
0154                return new String(buf, charPos, (33 - charPos));
0155            }
0156
0157            /**
0158             * Returns a string representation of the integer argument as an
0159             * unsigned integer in base&nbsp;16.
0160             * 
0161             * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
0162             * if the argument is negative; otherwise, it is equal to the
0163             * argument.  This value is converted to a string of ASCII digits
0164             * in hexadecimal (base&nbsp;16) with no extra leading
0165             * {@code 0}s. If the unsigned magnitude is zero, it is
0166             * represented by a single zero character {@code '0'}
0167             * (<code>'&#92;u0030'</code>); otherwise, the first character of
0168             * the representation of the unsigned magnitude will not be the
0169             * zero character. The following characters are used as
0170             * hexadecimal digits:
0171             *
0172             * <blockquote>
0173             *  {@code 0123456789abcdef}
0174             * </blockquote>
0175             *
0176             * These are the characters <code>'&#92;u0030'</code> through
0177             * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through
0178             * <code>'&#92;u0066'</code>. If uppercase letters are
0179             * desired, the {@link java.lang.String#toUpperCase()} method may
0180             * be called on the result:
0181             *
0182             * <blockquote>
0183             *  {@code Integer.toHexString(n).toUpperCase()}
0184             * </blockquote>
0185             *
0186             * @param   i   an integer to be converted to a string.
0187             * @return  the string representation of the unsigned integer value
0188             *          represented by the argument in hexadecimal (base&nbsp;16).
0189             * @since   JDK1.0.2
0190             */
0191            public static String toHexString(int i) {
0192                return toUnsignedString(i, 4);
0193            }
0194
0195            /**
0196             * Returns a string representation of the integer argument as an
0197             * unsigned integer in base&nbsp;8.
0198             * 
0199             * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
0200             * if the argument is negative; otherwise, it is equal to the
0201             * argument.  This value is converted to a string of ASCII digits
0202             * in octal (base&nbsp;8) with no extra leading {@code 0}s.
0203             * 
0204             * <p>If the unsigned magnitude is zero, it is represented by a
0205             * single zero character {@code '0'}
0206             * (<code>'&#92;u0030'</code>); otherwise, the first character of
0207             * the representation of the unsigned magnitude will not be the
0208             * zero character. The following characters are used as octal
0209             * digits:
0210             *
0211             * <blockquote>
0212             * {@code 01234567}
0213             * </blockquote>
0214             *
0215             * These are the characters <code>'&#92;u0030'</code> through
0216             * <code>'&#92;u0037'</code>.
0217             *
0218             * @param   i   an integer to be converted to a string.
0219             * @return  the string representation of the unsigned integer value
0220             *          represented by the argument in octal (base&nbsp;8).
0221             * @since   JDK1.0.2
0222             */
0223            public static String toOctalString(int i) {
0224                return toUnsignedString(i, 3);
0225            }
0226
0227            /**
0228             * Returns a string representation of the integer argument as an
0229             * unsigned integer in base&nbsp;2.
0230             * 
0231             * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
0232             * if the argument is negative; otherwise it is equal to the
0233             * argument.  This value is converted to a string of ASCII digits
0234             * in binary (base&nbsp;2) with no extra leading {@code 0}s.
0235             * If the unsigned magnitude is zero, it is represented by a
0236             * single zero character {@code '0'}
0237             * (<code>'&#92;u0030'</code>); otherwise, the first character of
0238             * the representation of the unsigned magnitude will not be the
0239             * zero character. The characters {@code '0'}
0240             * (<code>'&#92;u0030'</code>) and {@code '1'}
0241             * (<code>'&#92;u0031'</code>) are used as binary digits.
0242             *
0243             * @param   i   an integer to be converted to a string.
0244             * @return  the string representation of the unsigned integer value
0245             *          represented by the argument in binary (base&nbsp;2).
0246             * @since   JDK1.0.2
0247             */
0248            public static String toBinaryString(int i) {
0249                return toUnsignedString(i, 1);
0250            }
0251
0252            /**
0253             * Convert the integer to an unsigned number.
0254             */
0255            private static String toUnsignedString(int i, int shift) {
0256                char[] buf = new char[32];
0257                int charPos = 32;
0258                int radix = 1 << shift;
0259                int mask = radix - 1;
0260                do {
0261                    buf[--charPos] = digits[i & mask];
0262                    i >>>= shift;
0263                } while (i != 0);
0264
0265                return new String(buf, charPos, (32 - charPos));
0266            }
0267
0268            final static char[] DigitTens = { '0', '0', '0', '0', '0', '0',
0269                    '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1',
0270                    '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
0271                    '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4',
0272                    '4', '4', '4', '4', '4', '4', '4', '4', '5', '5', '5', '5',
0273                    '5', '5', '5', '5', '5', '5', '6', '6', '6', '6', '6', '6',
0274                    '6', '6', '6', '6', '7', '7', '7', '7', '7', '7', '7', '7',
0275                    '7', '7', '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
0276                    '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', };
0277
0278            final static char[] DigitOnes = { '0', '1', '2', '3', '4', '5',
0279                    '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7',
0280                    '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
0281                    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1',
0282                    '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3',
0283                    '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5',
0284                    '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7',
0285                    '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
0286                    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', };
0287
0288            // I use the "invariant division by multiplication" trick to
0289            // accelerate Integer.toString.  In particular we want to
0290            // avoid division by 10.
0291            //
0292            // The "trick" has roughly the same performance characteristics
0293            // as the "classic" Integer.toString code on a non-JIT VM.
0294            // The trick avoids .rem and .div calls but has a longer code
0295            // path and is thus dominated by dispatch overhead.  In the
0296            // JIT case the dispatch overhead doesn't exist and the
0297            // "trick" is considerably faster than the classic code.
0298            //
0299            // TODO-FIXME: convert (x * 52429) into the equiv shift-add
0300            // sequence.
0301            //
0302            // RE:  Division by Invariant Integers using Multiplication
0303            //      T Gralund, P Montgomery
0304            //      ACM PLDI 1994
0305            //
0306
0307            /**
0308             * Returns a {@code String} object representing the
0309             * specified integer. The argument is converted to signed decimal
0310             * representation and returned as a string, exactly as if the
0311             * argument and radix 10 were given as arguments to the {@link
0312             * #toString(int, int)} method.
0313             *
0314             * @param   i   an integer to be converted.
0315             * @return  a string representation of the argument in base&nbsp;10.
0316             */
0317            public static String toString(int i) {
0318                if (i == Integer.MIN_VALUE)
0319                    return "-2147483648";
0320                int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
0321                char[] buf = new char[size];
0322                getChars(i, size, buf);
0323                return new String(0, size, buf);
0324            }
0325
0326            /**
0327             * Places characters representing the integer i into the
0328             * character array buf. The characters are placed into
0329             * the buffer backwards starting with the least significant
0330             * digit at the specified index (exclusive), and working
0331             * backwards from there.
0332             *
0333             * Will fail if i == Integer.MIN_VALUE
0334             */
0335            static void getChars(int i, int index, char[] buf) {
0336                int q, r;
0337                int charPos = index;
0338                char sign = 0;
0339
0340                if (i < 0) {
0341                    sign = '-';
0342                    i = -i;
0343                }
0344
0345                // Generate two digits per iteration
0346                while (i >= 65536) {
0347                    q = i / 100;
0348                    // really: r = i - (q * 100);
0349                    r = i - ((q << 6) + (q << 5) + (q << 2));
0350                    i = q;
0351                    buf[--charPos] = DigitOnes[r];
0352                    buf[--charPos] = DigitTens[r];
0353                }
0354
0355                // Fall thru to fast mode for smaller numbers
0356                // assert(i <= 65536, i);
0357                for (;;) {
0358                    q = (i * 52429) >>> (16 + 3);
0359                    r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...
0360                    buf[--charPos] = digits[r];
0361                    i = q;
0362                    if (i == 0)
0363                        break;
0364                }
0365                if (sign != 0) {
0366                    buf[--charPos] = sign;
0367                }
0368            }
0369
0370            final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999,
0371                    9999999, 99999999, 999999999, Integer.MAX_VALUE };
0372
0373            // Requires positive x
0374            static int stringSize(int x) {
0375                for (int i = 0;; i++)
0376                    if (x <= sizeTable[i])
0377                        return i + 1;
0378            }
0379
0380            /**
0381             * Parses the string argument as a signed integer in the radix
0382             * specified by the second argument. The characters in the string
0383             * must all be digits of the specified radix (as determined by
0384             * whether {@link java.lang.Character#digit(char, int)} returns a
0385             * nonnegative value), except that the first character may be an
0386             * ASCII minus sign {@code '-'} (<code>'&#92;u002D'</code>) to
0387             * indicate a negative value or an ASCII plus sign {@code '+'}
0388             * (<code>'&#92;u002B'</code>) to indicate a positive value. The
0389             * resulting integer value is returned.
0390             * 
0391             * <p>An exception of type {@code NumberFormatException} is
0392             * thrown if any of the following situations occurs:
0393             * <ul>
0394             * <li>The first argument is {@code null} or is a string of
0395             * length zero.
0396             *
0397             * <li>The radix is either smaller than 
0398             * {@link java.lang.Character#MIN_RADIX} or
0399             * larger than {@link java.lang.Character#MAX_RADIX}. 
0400             *
0401             * <li>Any character of the string is not a digit of the specified
0402             * radix, except that the first character may be a minus sign
0403             * {@code '-'} (<code>'&#92;u002D'</code>) or plus sign
0404             * {@code '+'} (<code>'&#92;u002B'</code>) provided that the
0405             * string is longer than length 1.
0406             *
0407             * <li>The value represented by the string is not a value of type
0408             * {@code int}. 
0409             * </ul>
0410             *
0411             * <p>Examples:
0412             * <blockquote><pre>
0413             * parseInt("0", 10) returns 0
0414             * parseInt("473", 10) returns 473
0415             * parseInt("+42", 10) returns 42
0416             * parseInt("-0", 10) returns 0
0417             * parseInt("-FF", 16) returns -255
0418             * parseInt("1100110", 2) returns 102
0419             * parseInt("2147483647", 10) returns 2147483647
0420             * parseInt("-2147483648", 10) returns -2147483648
0421             * parseInt("2147483648", 10) throws a NumberFormatException
0422             * parseInt("99", 8) throws a NumberFormatException
0423             * parseInt("Kona", 10) throws a NumberFormatException
0424             * parseInt("Kona", 27) returns 411787
0425             * </pre></blockquote>
0426             *
0427             * @param      s   the {@code String} containing the integer 
0428             * 			representation to be parsed
0429             * @param      radix   the radix to be used while parsing {@code s}.
0430             * @return     the integer represented by the string argument in the
0431             *             specified radix.
0432             * @exception  NumberFormatException if the {@code String}
0433             * 		   does not contain a parsable {@code int}.
0434             */
0435            public static int parseInt(String s, int radix)
0436                    throws NumberFormatException {
0437                if (s == null) {
0438                    throw new NumberFormatException("null");
0439                }
0440
0441                if (radix < Character.MIN_RADIX) {
0442                    throw new NumberFormatException("radix " + radix
0443                            + " less than Character.MIN_RADIX");
0444                }
0445
0446                if (radix > Character.MAX_RADIX) {
0447                    throw new NumberFormatException("radix " + radix
0448                            + " greater than Character.MAX_RADIX");
0449                }
0450
0451                int result = 0;
0452                boolean negative = false;
0453                int i = 0, len = s.length();
0454                int limit = -Integer.MAX_VALUE;
0455                int multmin;
0456                int digit;
0457
0458                if (len > 0) {
0459                    char firstChar = s.charAt(0);
0460                    if (firstChar < '0') { // Possible leading "+" or "-"
0461                        if (firstChar == '-') {
0462                            negative = true;
0463                            limit = Integer.MIN_VALUE;
0464                        } else if (firstChar != '+')
0465                            throw NumberFormatException.forInputString(s);
0466
0467                        if (len == 1) // Cannot have lone "+" or "-"
0468                            throw NumberFormatException.forInputString(s);
0469                        i++;
0470                    }
0471                    multmin = limit / radix;
0472                    while (i < len) {
0473                        // Accumulating negatively avoids surprises near MAX_VALUE
0474                        digit = Character.digit(s.charAt(i++), radix);
0475                        if (digit < 0) {
0476                            throw NumberFormatException.forInputString(s);
0477                        }
0478                        if (result < multmin) {
0479                            throw NumberFormatException.forInputString(s);
0480                        }
0481                        result *= radix;
0482                        if (result < limit + digit) {
0483                            throw NumberFormatException.forInputString(s);
0484                        }
0485                        result -= digit;
0486                    }
0487                } else {
0488                    throw NumberFormatException.forInputString(s);
0489                }
0490                return negative ? result : -result;
0491            }
0492
0493            /**
0494             * Parses the string argument as a signed decimal integer. The
0495             * characters in the string must all be decimal digits, except
0496             * that the first character may be an ASCII minus sign {@code '-'}
0497             * (<code>'&#92;u002D'</code>) to indicate a negative value or an
0498             * ASCII plus sign {@code '+'} (<code>'&#92;u002B'</code>) to
0499             * indicate a positive value. The resulting integer value is
0500             * returned, exactly as if the argument and the radix 10 were
0501             * given as arguments to the {@link #parseInt(java.lang.String,
0502             * int)} method.
0503             *
0504             * @param s	   a {@code String} containing the {@code int}
0505             *             representation to be parsed
0506             * @return     the integer value represented by the argument in decimal.
0507             * @exception  NumberFormatException  if the string does not contain a
0508             *               parsable integer.
0509             */
0510            public static int parseInt(String s) throws NumberFormatException {
0511                return parseInt(s, 10);
0512            }
0513
0514            /**
0515             * Returns an {@code Integer} object holding the value
0516             * extracted from the specified {@code String} when parsed
0517             * with the radix given by the second argument. The first argument
0518             * is interpreted as representing a signed integer in the radix
0519             * specified by the second argument, exactly as if the arguments
0520             * were given to the {@link #parseInt(java.lang.String, int)}
0521             * method. The result is an {@code Integer} object that
0522             * represents the integer value specified by the string.
0523             * 
0524             * <p>In other words, this method returns an {@code Integer}
0525             * object equal to the value of:
0526             *
0527             * <blockquote>
0528             *  {@code new Integer(Integer.parseInt(s, radix))}
0529             * </blockquote>
0530             *
0531             * @param      s   the string to be parsed.
0532             * @param      radix the radix to be used in interpreting {@code s}
0533             * @return     an {@code Integer} object holding the value
0534             *             represented by the string argument in the specified
0535             *             radix.
0536             * @exception NumberFormatException if the {@code String}
0537             * 		  does not contain a parsable {@code int}.
0538             */
0539            public static Integer valueOf(String s, int radix)
0540                    throws NumberFormatException {
0541                return new Integer(parseInt(s, radix));
0542            }
0543
0544            /**
0545             * Returns an {@code Integer} object holding the
0546             * value of the specified {@code String}. The argument is
0547             * interpreted as representing a signed decimal integer, exactly
0548             * as if the argument were given to the {@link
0549             * #parseInt(java.lang.String)} method. The result is an
0550             * {@code Integer} object that represents the integer value
0551             * specified by the string.
0552             * 
0553             * <p>In other words, this method returns an {@code Integer}
0554             * object equal to the value of:
0555             *
0556             * <blockquote>
0557             *  {@code new Integer(Integer.parseInt(s))}
0558             * </blockquote>
0559             *
0560             * @param      s   the string to be parsed.
0561             * @return     an {@code Integer} object holding the value
0562             *             represented by the string argument.
0563             * @exception  NumberFormatException  if the string cannot be parsed 
0564             *             as an integer.
0565             */
0566            public static Integer valueOf(String s)
0567                    throws NumberFormatException {
0568                return new Integer(parseInt(s, 10));
0569            }
0570
0571            private static class IntegerCache {
0572                private IntegerCache() {
0573                }
0574
0575                static final Integer cache[] = new Integer[-(-128) + 127 + 1];
0576
0577                static {
0578                    for (int i = 0; i < cache.length; i++)
0579                        cache[i] = new Integer(i - 128);
0580                }
0581            }
0582
0583            /**
0584             * Returns an {@code Integer} instance representing the specified
0585             * {@code int} value.  If a new {@code Integer} instance is not
0586             * required, this method should generally be used in preference to
0587             * the constructor {@link #Integer(int)}, as this method is likely
0588             * to yield significantly better space and time performance by
0589             * caching frequently requested values.
0590             *
0591             * @param  i an {@code int} value.
0592             * @return an {@code Integer} instance representing {@code i}.
0593             * @since  1.5
0594             */
0595            public static Integer valueOf(int i) {
0596                final int offset = 128;
0597                if (i >= -128 && i <= 127) { // must cache 
0598                    return IntegerCache.cache[i + offset];
0599                }
0600                return new Integer(i);
0601            }
0602
0603            /**
0604             * The value of the {@code Integer}.
0605             *
0606             * @serial
0607             */
0608            private final int value;
0609
0610            /**
0611             * Constructs a newly allocated {@code Integer} object that
0612             * represents the specified {@code int} value.
0613             *
0614             * @param   value   the value to be represented by the 
0615             *			{@code Integer} object.
0616             */
0617            public Integer(int value) {
0618                this .value = value;
0619            }
0620
0621            /**
0622             * Constructs a newly allocated {@code Integer} object that
0623             * represents the {@code int} value indicated by the
0624             * {@code String} parameter. The string is converted to an
0625             * {@code int} value in exactly the manner used by the
0626             * {@code parseInt} method for radix 10.
0627             *
0628             * @param      s   the {@code String} to be converted to an
0629             *                 {@code Integer}.
0630             * @exception  NumberFormatException  if the {@code String} does not
0631             *               contain a parsable integer.
0632             * @see        java.lang.Integer#parseInt(java.lang.String, int)
0633             */
0634            public Integer(String s) throws NumberFormatException {
0635                this .value = parseInt(s, 10);
0636            }
0637
0638            /**
0639             * Returns the value of this {@code Integer} as a
0640             * {@code byte}.
0641             */
0642            public byte byteValue() {
0643                return (byte) value;
0644            }
0645
0646            /**
0647             * Returns the value of this {@code Integer} as a
0648             * {@code short}.
0649             */
0650            public short shortValue() {
0651                return (short) value;
0652            }
0653
0654            /**
0655             * Returns the value of this {@code Integer} as an
0656             * {@code int}.
0657             */
0658            public int intValue() {
0659                return value;
0660            }
0661
0662            /**
0663             * Returns the value of this {@code Integer} as a
0664             * {@code long}.
0665             */
0666            public long longValue() {
0667                return (long) value;
0668            }
0669
0670            /**
0671             * Returns the value of this {@code Integer} as a
0672             * {@code float}.
0673             */
0674            public float floatValue() {
0675                return (float) value;
0676            }
0677
0678            /**
0679             * Returns the value of this {@code Integer} as a
0680             * {@code double}.
0681             */
0682            public double doubleValue() {
0683                return (double) value;
0684            }
0685
0686            /**
0687             * Returns a {@code String} object representing this
0688             * {@code Integer}'s value. The value is converted to signed
0689             * decimal representation and returned as a string, exactly as if
0690             * the integer value were given as an argument to the {@link
0691             * java.lang.Integer#toString(int)} method.
0692             *
0693             * @return  a string representation of the value of this object in
0694             *          base&nbsp;10.
0695             */
0696            public String toString() {
0697                return String.valueOf(value);
0698            }
0699
0700            /**
0701             * Returns a hash code for this {@code Integer}.
0702             *
0703             * @return  a hash code value for this object, equal to the 
0704             *          primitive {@code int} value represented by this 
0705             *          {@code Integer} object. 
0706             */
0707            public int hashCode() {
0708                return value;
0709            }
0710
0711            /**
0712             * Compares this object to the specified object.  The result is
0713             * {@code true} if and only if the argument is not
0714             * {@code null} and is an {@code Integer} object that
0715             * contains the same {@code int} value as this object.
0716             *
0717             * @param   obj   the object to compare with.
0718             * @return  {@code true} if the objects are the same;
0719             *          {@code false} otherwise.
0720             */
0721            public boolean equals(Object obj) {
0722                if (obj instanceof  Integer) {
0723                    return value == ((Integer) obj).intValue();
0724                }
0725                return false;
0726            }
0727
0728            /**
0729             * Determines the integer value of the system property with the
0730             * specified name.
0731             * 
0732             * <p>The first argument is treated as the name of a system property. 
0733             * System properties are accessible through the 
0734             * {@link java.lang.System#getProperty(java.lang.String)} method. The 
0735             * string value of this property is then interpreted as an integer 
0736             * value and an {@code Integer} object representing this value is 
0737             * returned. Details of possible numeric formats can be found with 
0738             * the definition of {@code getProperty}. 
0739             * 
0740             * <p>If there is no property with the specified name, if the specified name
0741             * is empty or {@code null}, or if the property does not have 
0742             * the correct numeric format, then {@code null} is returned.
0743             * 
0744             * <p>In other words, this method returns an {@code Integer}
0745             * object equal to the value of:
0746             *
0747             * <blockquote>
0748             *  {@code getInteger(nm, null)}
0749             * </blockquote>
0750             *
0751             * @param   nm   property name.
0752             * @return  the {@code Integer} value of the property.
0753             * @see     java.lang.System#getProperty(java.lang.String)
0754             * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
0755             */
0756            public static Integer getInteger(String nm) {
0757                return getInteger(nm, null);
0758            }
0759
0760            /**
0761             * Determines the integer value of the system property with the
0762             * specified name.
0763             * 
0764             * <p>The first argument is treated as the name of a system property.
0765             * System properties are accessible through the {@link
0766             * java.lang.System#getProperty(java.lang.String)} method. The 
0767             * string value of this property is then interpreted as an integer 
0768             * value and an {@code Integer} object representing this value is 
0769             * returned. Details of possible numeric formats can be found with 
0770             * the definition of {@code getProperty}. 
0771             * 
0772             * <p>The second argument is the default value. An {@code Integer} object
0773             * that represents the value of the second argument is returned if there
0774             * is no property of the specified name, if the property does not have
0775             * the correct numeric format, or if the specified name is empty or
0776             * {@code null}.
0777             * 
0778             * <p>In other words, this method returns an {@code Integer} object 
0779             * equal to the value of:
0780             *
0781             * <blockquote>
0782             *  {@code getInteger(nm, new Integer(val))}
0783             * </blockquote>
0784             *
0785             * but in practice it may be implemented in a manner such as: 
0786             *
0787             * <blockquote><pre>
0788             * Integer result = getInteger(nm, null);
0789             * return (result == null) ? new Integer(val) : result;
0790             * </pre></blockquote>
0791             *
0792             * to avoid the unnecessary allocation of an {@code Integer} 
0793             * object when the default value is not needed. 
0794             *
0795             * @param   nm   property name.
0796             * @param   val   default value.
0797             * @return  the {@code Integer} value of the property.
0798             * @see     java.lang.System#getProperty(java.lang.String)
0799             * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
0800             */
0801            public static Integer getInteger(String nm, int val) {
0802                Integer result = getInteger(nm, null);
0803                return (result == null) ? new Integer(val) : result;
0804            }
0805
0806            /**
0807             * Returns the integer value of the system property with the
0808             * specified name.  The first argument is treated as the name of a
0809             * system property.  System properties are accessible through the
0810             * {@link java.lang.System#getProperty(java.lang.String)} method.
0811             * The string value of this property is then interpreted as an
0812             * integer value, as per the {@code Integer.decode} method,
0813             * and an {@code Integer} object representing this value is
0814             * returned.
0815             *
0816             * <ul><li>If the property value begins with the two ASCII characters 
0817             *         {@code 0x} or the ASCII character {@code #}, not 
0818             *      followed by a minus sign, then the rest of it is parsed as a 
0819             *      hexadecimal integer exactly as by the method 
0820             *      {@link #valueOf(java.lang.String, int)} with radix 16. 
0821             * <li>If the property value begins with the ASCII character 
0822             *     {@code 0} followed by another character, it is parsed as an 
0823             *     octal integer exactly as by the method 
0824             *     {@link #valueOf(java.lang.String, int)} with radix 8. 
0825             * <li>Otherwise, the property value is parsed as a decimal integer 
0826             * exactly as by the method {@link #valueOf(java.lang.String, int)} 
0827             * with radix 10. 
0828             * </ul>
0829             *
0830             * <p>The second argument is the default value. The default value is
0831             * returned if there is no property of the specified name, if the
0832             * property does not have the correct numeric format, or if the
0833             * specified name is empty or {@code null}.
0834             *
0835             * @param   nm   property name.
0836             * @param   val   default value.
0837             * @return  the {@code Integer} value of the property.
0838             * @see     java.lang.System#getProperty(java.lang.String)
0839             * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
0840             * @see java.lang.Integer#decode
0841             */
0842            public static Integer getInteger(String nm, Integer val) {
0843                String v = null;
0844                try {
0845                    v = System.getProperty(nm);
0846                } catch (IllegalArgumentException e) {
0847                } catch (NullPointerException e) {
0848                }
0849                if (v != null) {
0850                    try {
0851                        return Integer.decode(v);
0852                    } catch (NumberFormatException e) {
0853                    }
0854                }
0855                return val;
0856            }
0857
0858            /**
0859             * Decodes a {@code String} into an {@code Integer}.
0860             * Accepts decimal, hexadecimal, and octal numbers given
0861             * by the following grammar:
0862             *
0863             * <blockquote>
0864             * <dl>
0865             * <dt><i>DecodableString:</i>
0866             * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
0867             * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
0868             * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
0869             * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
0870             * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
0871             * <p>
0872             * <dt><i>Sign:</i>
0873             * <dd>{@code -}
0874             * <dd>{@code +}
0875             * </dl>
0876             * </blockquote>
0877             *
0878             * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
0879             * are defined in <a href="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48282">&sect;3.10.1</a> 
0880             * of the <a href="http://java.sun.com/docs/books/jls/html/">Java 
0881             * Language Specification</a>.
0882             * 
0883             * <p>The sequence of characters following an optional
0884             * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
0885             * "{@code #}", or leading zero) is parsed as by the {@code
0886             * Integer.parseInt} method with the indicated radix (10, 16, or
0887             * 8).  This sequence of characters must represent a positive
0888             * value or a {@link NumberFormatException} will be thrown.  The
0889             * result is negated if first character of the specified {@code
0890             * String} is the minus sign.  No whitespace characters are
0891             * permitted in the {@code String}.
0892             *
0893             * @param     nm the {@code String} to decode.
0894             * @return    an {@code Integer} object holding the {@code int}
0895             *		   value represented by {@code nm}
0896             * @exception NumberFormatException  if the {@code String} does not
0897             *            contain a parsable integer.
0898             * @see java.lang.Integer#parseInt(java.lang.String, int)
0899             */
0900            public static Integer decode(String nm)
0901                    throws NumberFormatException {
0902                int radix = 10;
0903                int index = 0;
0904                boolean negative = false;
0905                Integer result;
0906
0907                if (nm.length() == 0)
0908                    throw new NumberFormatException("Zero length string");
0909                char firstChar = nm.charAt(0);
0910                // Handle sign, if present
0911                if (firstChar == '-') {
0912                    negative = true;
0913                    index++;
0914                } else if (firstChar == '+')
0915                    index++;
0916
0917                // Handle radix specifier, if present
0918                if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
0919                    index += 2;
0920                    radix = 16;
0921                } else if (nm.startsWith("#", index)) {
0922                    index++;
0923                    radix = 16;
0924                } else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
0925                    index++;
0926                    radix = 8;
0927                }
0928
0929                if (nm.startsWith("-", index) || nm.startsWith("+", index))
0930                    throw new NumberFormatException(
0931                            "Sign character in wrong position");
0932
0933                try {
0934                    result = Integer.valueOf(nm.substring(index), radix);
0935                    result = negative ? new Integer(-result.intValue())
0936                            : result;
0937                } catch (NumberFormatException e) {
0938                    // If number is Integer.MIN_VALUE, we'll end up here. The next line
0939                    // handles this case, and causes any genuine format error to be
0940                    // rethrown.
0941                    String constant = negative ? ("-" + nm.substring(index))
0942                            : nm.substring(index);
0943                    result = Integer.valueOf(constant, radix);
0944                }
0945                return result;
0946            }
0947
0948            /**
0949             * Compares two {@code Integer} objects numerically.
0950             *
0951             * @param   anotherInteger   the {@code Integer} to be compared.
0952             * @return	the value {@code 0} if this {@code Integer} is
0953             * 		equal to the argument {@code Integer}; a value less than
0954             * 		{@code 0} if this {@code Integer} is numerically less
0955             * 		than the argument {@code Integer}; and a value greater 
0956             * 		than {@code 0} if this {@code Integer} is numerically
0957             * 		 greater than the argument {@code Integer} (signed
0958             * 		 comparison).
0959             * @since   1.2
0960             */
0961            public int compareTo(Integer anotherInteger) {
0962                int this Val = this .value;
0963                int anotherVal = anotherInteger.value;
0964                return (this Val < anotherVal ? -1 : (this Val == anotherVal ? 0
0965                        : 1));
0966            }
0967
0968            // Bit twiddling
0969
0970            /**
0971             * The number of bits used to represent an {@code int} value in two's
0972             * complement binary form.
0973             *
0974             * @since 1.5
0975             */
0976            public static final int SIZE = 32;
0977
0978            /**
0979             * Returns an {@code int} value with at most a single one-bit, in the
0980             * position of the highest-order ("leftmost") one-bit in the specified
0981             * {@code int} value.  Returns zero if the specified value has no
0982             * one-bits in its two's complement binary representation, that is, if it
0983             * is equal to zero.
0984             *
0985             * @return an {@code int} value with a single one-bit, in the position
0986             *     of the highest-order one-bit in the specified value, or zero if
0987             *     the specified value is itself equal to zero.
0988             * @since 1.5
0989             */
0990            public static int highestOneBit(int i) {
0991                // HD, Figure 3-1
0992                i |= (i >> 1);
0993                i |= (i >> 2);
0994                i |= (i >> 4);
0995                i |= (i >> 8);
0996                i |= (i >> 16);
0997                return i - (i >>> 1);
0998            }
0999
1000            /**
1001             * Returns an {@code int} value with at most a single one-bit, in the
1002             * position of the lowest-order ("rightmost") one-bit in the specified
1003             * {@code int} value.  Returns zero if the specified value has no
1004             * one-bits in its two's complement binary representation, that is, if it
1005             * is equal to zero.
1006             *
1007             * @return an {@code int} value with a single one-bit, in the position
1008             *     of the lowest-order one-bit in the specified value, or zero if
1009             *     the specified value is itself equal to zero.
1010             * @since 1.5
1011             */
1012            public static int lowestOneBit(int i) {
1013                // HD, Section 2-1
1014                return i & -i;
1015            }
1016
1017            /**
1018             * Returns the number of zero bits preceding the highest-order
1019             * ("leftmost") one-bit in the two's complement binary representation
1020             * of the specified {@code int} value.  Returns 32 if the
1021             * specified value has no one-bits in its two's complement representation,
1022             * in other words if it is equal to zero.
1023             *
1024             * <p>Note that this method is closely related to the logarithm base 2.
1025             * For all positive {@code int} values x:
1026             * <ul>
1027             * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}
1028             * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}
1029             * </ul>
1030             *
1031             * @return the number of zero bits preceding the highest-order
1032             *     ("leftmost") one-bit in the two's complement binary representation
1033             *     of the specified {@code int} value, or 32 if the value
1034             *     is equal to zero.
1035             * @since 1.5
1036             */
1037            public static int numberOfLeadingZeros(int i) {
1038                // HD, Figure 5-6
1039                if (i == 0)
1040                    return 32;
1041                int n = 1;
1042                if (i >>> 16 == 0) {
1043                    n += 16;
1044                    i <<= 16;
1045                }
1046                if (i >>> 24 == 0) {
1047                    n += 8;
1048                    i <<= 8;
1049                }
1050                if (i >>> 28 == 0) {
1051                    n += 4;
1052                    i <<= 4;
1053                }
1054                if (i >>> 30 == 0) {
1055                    n += 2;
1056                    i <<= 2;
1057                }
1058                n -= i >>> 31;
1059                return n;
1060            }
1061
1062            /**
1063             * Returns the number of zero bits following the lowest-order ("rightmost")
1064             * one-bit in the two's complement binary representation of the specified
1065             * {@code int} value.  Returns 32 if the specified value has no
1066             * one-bits in its two's complement representation, in other words if it is
1067             * equal to zero.
1068             *
1069             * @return the number of zero bits following the lowest-order ("rightmost")
1070             *     one-bit in the two's complement binary representation of the
1071             *     specified {@code int} value, or 32 if the value is equal
1072             *     to zero.
1073             * @since 1.5
1074             */
1075            public static int numberOfTrailingZeros(int i) {
1076                // HD, Figure 5-14
1077                int y;
1078                if (i == 0)
1079                    return 32;
1080                int n = 31;
1081                y = i << 16;
1082                if (y != 0) {
1083                    n = n - 16;
1084                    i = y;
1085                }
1086                y = i << 8;
1087                if (y != 0) {
1088                    n = n - 8;
1089                    i = y;
1090                }
1091                y = i << 4;
1092                if (y != 0) {
1093                    n = n - 4;
1094                    i = y;
1095                }
1096                y = i << 2;
1097                if (y != 0) {
1098                    n = n - 2;
1099                    i = y;
1100                }
1101                return n - ((i << 1) >>> 31);
1102            }
1103
1104            /**
1105             * Returns the number of one-bits in the two's complement binary
1106             * representation of the specified {@code int} value.  This function is
1107             * sometimes referred to as the <i>population count</i>.
1108             *
1109             * @return the number of one-bits in the two's complement binary
1110             *     representation of the specified {@code int} value.
1111             * @since 1.5
1112             */
1113            public static int bitCount(int i) {
1114                // HD, Figure 5-2
1115                i = i - ((i >>> 1) & 0x55555555);
1116                i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
1117                i = (i + (i >>> 4)) & 0x0f0f0f0f;
1118                i = i + (i >>> 8);
1119                i = i + (i >>> 16);
1120                return i & 0x3f;
1121            }
1122
1123            /**
1124             * Returns the value obtained by rotating the two's complement binary
1125             * representation of the specified {@code int} value left by the
1126             * specified number of bits.  (Bits shifted out of the left hand, or
1127             * high-order, side reenter on the right, or low-order.)
1128             *
1129             * <p>Note that left rotation with a negative distance is equivalent to
1130             * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
1131             * distance)}.  Note also that rotation by any multiple of 32 is a
1132             * no-op, so all but the last five bits of the rotation distance can be
1133             * ignored, even if the distance is negative: {@code rotateLeft(val,
1134             * distance) == rotateLeft(val, distance & 0x1F)}.
1135             *
1136             * @return the value obtained by rotating the two's complement binary
1137             *     representation of the specified {@code int} value left by the
1138             *     specified number of bits.
1139             * @since 1.5
1140             */
1141            public static int rotateLeft(int i, int distance) {
1142                return (i << distance) | (i >>> -distance);
1143            }
1144
1145            /**
1146             * Returns the value obtained by rotating the two's complement binary
1147             * representation of the specified {@code int} value right by the
1148             * specified number of bits.  (Bits shifted out of the right hand, or
1149             * low-order, side reenter on the left, or high-order.)
1150             *
1151             * <p>Note that right rotation with a negative distance is equivalent to
1152             * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
1153             * distance)}.  Note also that rotation by any multiple of 32 is a
1154             * no-op, so all but the last five bits of the rotation distance can be
1155             * ignored, even if the distance is negative: {@code rotateRight(val,
1156             * distance) == rotateRight(val, distance & 0x1F)}.
1157             *
1158             * @return the value obtained by rotating the two's complement binary
1159             *     representation of the specified {@code int} value right by the
1160             *     specified number of bits.
1161             * @since 1.5
1162             */
1163            public static int rotateRight(int i, int distance) {
1164                return (i >>> distance) | (i << -distance);
1165            }
1166
1167            /**
1168             * Returns the value obtained by reversing the order of the bits in the
1169             * two's complement binary representation of the specified {@code int}
1170             * value.
1171             *
1172             * @return the value obtained by reversing order of the bits in the
1173             *     specified {@code int} value.
1174             * @since 1.5
1175             */
1176            public static int reverse(int i) {
1177                // HD, Figure 7-1
1178                i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
1179                i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
1180                i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
1181                i = (i << 24) | ((i & 0xff00) << 8) | ((i >>> 8) & 0xff00)
1182                        | (i >>> 24);
1183                return i;
1184            }
1185
1186            /**
1187             * Returns the signum function of the specified {@code int} value.  (The
1188             * return value is -1 if the specified value is negative; 0 if the
1189             * specified value is zero; and 1 if the specified value is positive.)
1190             *
1191             * @return the signum function of the specified {@code int} value.
1192             * @since 1.5
1193             */
1194            public static int signum(int i) {
1195                // HD, Section 2-7
1196                return (i >> 31) | (-i >>> 31);
1197            }
1198
1199            /**
1200             * Returns the value obtained by reversing the order of the bytes in the
1201             * two's complement representation of the specified {@code int} value.
1202             *
1203             * @return the value obtained by reversing the bytes in the specified
1204             *     {@code int} value.
1205             * @since 1.5
1206             */
1207            public static int reverseBytes(int i) {
1208                return ((i >>> 24)) | ((i >> 8) & 0xFF00)
1209                        | ((i << 8) & 0xFF0000) | ((i << 24));
1210            }
1211
1212            /** use serialVersionUID from JDK 1.0.2 for interoperability */
1213            private static final long serialVersionUID = 1360826667806852920L;
1214        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.