Save This Page
Home » Open-JDK-6.b17-src » java » lang » [javadoc | source]
    1   /*
    2    * Copyright 1994-2006 Sun Microsystems, Inc.  All Rights Reserved.
    3    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    4    *
    5    * This code is free software; you can redistribute it and/or modify it
    6    * under the terms of the GNU General Public License version 2 only, as
    7    * published by the Free Software Foundation.  Sun designates this
    8    * particular file as subject to the "Classpath" exception as provided
    9    * by Sun in the LICENSE file that accompanied this code.
   10    *
   11    * This code is distributed in the hope that it will be useful, but WITHOUT
   12    * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   13    * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   14    * version 2 for more details (a copy is included in the LICENSE file that
   15    * accompanied this code).
   16    *
   17    * You should have received a copy of the GNU General Public License version
   18    * 2 along with this work; if not, write to the Free Software Foundation,
   19    * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   20    *
   21    * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   22    * CA 95054 USA or visit www.sun.com if you need additional information or
   23    * have any questions.
   24    */
   25   
   26   package java.lang;
   27   
   28   /**
   29    * The {@code Integer} class wraps a value of the primitive type
   30    * {@code int} in an object. An object of type {@code Integer}
   31    * contains a single field whose type is {@code int}.
   32    *
   33    * <p>In addition, this class provides several methods for converting
   34    * an {@code int} to a {@code String} and a {@code String} to an
   35    * {@code int}, as well as other constants and methods useful when
   36    * dealing with an {@code int}.
   37    *
   38    * <p>Implementation note: The implementations of the "bit twiddling"
   39    * methods (such as {@link #highestOneBit(int) highestOneBit} and
   40    * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are
   41    * based on material from Henry S. Warren, Jr.'s <i>Hacker's
   42    * Delight</i>, (Addison Wesley, 2002).
   43    *
   44    * @author  Lee Boynton
   45    * @author  Arthur van Hoff
   46    * @author  Josh Bloch
   47    * @author  Joseph D. Darcy
   48    * @since JDK1.0
   49    */
   50   public final class Integer extends Number implements Comparable<Integer> {
   51       /**
   52        * A constant holding the minimum value an {@code int} can
   53        * have, -2<sup>31</sup>.
   54        */
   55       public static final int   MIN_VALUE = 0x80000000;
   56   
   57       /**
   58        * A constant holding the maximum value an {@code int} can
   59        * have, 2<sup>31</sup>-1.
   60        */
   61       public static final int   MAX_VALUE = 0x7fffffff;
   62   
   63       /**
   64        * The {@code Class} instance representing the primitive type
   65        * {@code int}.
   66        *
   67        * @since   JDK1.1
   68        */
   69       public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
   70   
   71       /**
   72        * All possible chars for representing a number as a String
   73        */
   74       final static char[] digits = {
   75           '0' , '1' , '2' , '3' , '4' , '5' ,
   76           '6' , '7' , '8' , '9' , 'a' , 'b' ,
   77           'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
   78           'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
   79           'o' , 'p' , 'q' , 'r' , 's' , 't' ,
   80           'u' , 'v' , 'w' , 'x' , 'y' , 'z'
   81       };
   82   
   83       /**
   84        * Returns a string representation of the first argument in the
   85        * radix specified by the second argument.
   86        *
   87        * <p>If the radix is smaller than {@code Character.MIN_RADIX}
   88        * or larger than {@code Character.MAX_RADIX}, then the radix
   89        * {@code 10} is used instead.
   90        *
   91        * <p>If the first argument is negative, the first element of the
   92        * result is the ASCII minus character {@code '-'}
   93        * (<code>'&#92;u002D'</code>). If the first argument is not
   94        * negative, no sign character appears in the result.
   95        *
   96        * <p>The remaining characters of the result represent the magnitude
   97        * of the first argument. If the magnitude is zero, it is
   98        * represented by a single zero character {@code '0'}
   99        * (<code>'&#92;u0030'</code>); otherwise, the first character of
  100        * the representation of the magnitude will not be the zero
  101        * character.  The following ASCII characters are used as digits:
  102        *
  103        * <blockquote>
  104        *   {@code 0123456789abcdefghijklmnopqrstuvwxyz}
  105        * </blockquote>
  106        *
  107        * These are <code>'&#92;u0030'</code> through
  108        * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through
  109        * <code>'&#92;u007A'</code>. If {@code radix} is
  110        * <var>N</var>, then the first <var>N</var> of these characters
  111        * are used as radix-<var>N</var> digits in the order shown. Thus,
  112        * the digits for hexadecimal (radix 16) are
  113        * {@code 0123456789abcdef}. If uppercase letters are
  114        * desired, the {@link java.lang.String#toUpperCase()} method may
  115        * be called on the result:
  116        *
  117        * <blockquote>
  118        *  {@code Integer.toString(n, 16).toUpperCase()}
  119        * </blockquote>
  120        *
  121        * @param   i       an integer to be converted to a string.
  122        * @param   radix   the radix to use in the string representation.
  123        * @return  a string representation of the argument in the specified radix.
  124        * @see     java.lang.Character#MAX_RADIX
  125        * @see     java.lang.Character#MIN_RADIX
  126        */
  127       public static String toString(int i, int radix) {
  128   
  129           if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
  130               radix = 10;
  131   
  132           /* Use the faster version */
  133           if (radix == 10) {
  134               return toString(i);
  135           }
  136   
  137           char buf[] = new char[33];
  138           boolean negative = (i < 0);
  139           int charPos = 32;
  140   
  141           if (!negative) {
  142               i = -i;
  143           }
  144   
  145           while (i <= -radix) {
  146               buf[charPos--] = digits[-(i % radix)];
  147               i = i / radix;
  148           }
  149           buf[charPos] = digits[-i];
  150   
  151           if (negative) {
  152               buf[--charPos] = '-';
  153           }
  154   
  155           return new String(buf, charPos, (33 - charPos));
  156       }
  157   
  158       /**
  159        * Returns a string representation of the integer argument as an
  160        * unsigned integer in base&nbsp;16.
  161        *
  162        * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
  163        * if the argument is negative; otherwise, it is equal to the
  164        * argument.  This value is converted to a string of ASCII digits
  165        * in hexadecimal (base&nbsp;16) with no extra leading
  166        * {@code 0}s. If the unsigned magnitude is zero, it is
  167        * represented by a single zero character {@code '0'}
  168        * (<code>'&#92;u0030'</code>); otherwise, the first character of
  169        * the representation of the unsigned magnitude will not be the
  170        * zero character. The following characters are used as
  171        * hexadecimal digits:
  172        *
  173        * <blockquote>
  174        *  {@code 0123456789abcdef}
  175        * </blockquote>
  176        *
  177        * These are the characters <code>'&#92;u0030'</code> through
  178        * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through
  179        * <code>'&#92;u0066'</code>. If uppercase letters are
  180        * desired, the {@link java.lang.String#toUpperCase()} method may
  181        * be called on the result:
  182        *
  183        * <blockquote>
  184        *  {@code Integer.toHexString(n).toUpperCase()}
  185        * </blockquote>
  186        *
  187        * @param   i   an integer to be converted to a string.
  188        * @return  the string representation of the unsigned integer value
  189        *          represented by the argument in hexadecimal (base&nbsp;16).
  190        * @since   JDK1.0.2
  191        */
  192       public static String toHexString(int i) {
  193           return toUnsignedString(i, 4);
  194       }
  195   
  196       /**
  197        * Returns a string representation of the integer argument as an
  198        * unsigned integer in base&nbsp;8.
  199        *
  200        * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
  201        * if the argument is negative; otherwise, it is equal to the
  202        * argument.  This value is converted to a string of ASCII digits
  203        * in octal (base&nbsp;8) with no extra leading {@code 0}s.
  204        *
  205        * <p>If the unsigned magnitude is zero, it is represented by a
  206        * single zero character {@code '0'}
  207        * (<code>'&#92;u0030'</code>); otherwise, the first character of
  208        * the representation of the unsigned magnitude will not be the
  209        * zero character. The following characters are used as octal
  210        * digits:
  211        *
  212        * <blockquote>
  213        * {@code 01234567}
  214        * </blockquote>
  215        *
  216        * These are the characters <code>'&#92;u0030'</code> through
  217        * <code>'&#92;u0037'</code>.
  218        *
  219        * @param   i   an integer to be converted to a string.
  220        * @return  the string representation of the unsigned integer value
  221        *          represented by the argument in octal (base&nbsp;8).
  222        * @since   JDK1.0.2
  223        */
  224       public static String toOctalString(int i) {
  225           return toUnsignedString(i, 3);
  226       }
  227   
  228       /**
  229        * Returns a string representation of the integer argument as an
  230        * unsigned integer in base&nbsp;2.
  231        *
  232        * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
  233        * if the argument is negative; otherwise it is equal to the
  234        * argument.  This value is converted to a string of ASCII digits
  235        * in binary (base&nbsp;2) with no extra leading {@code 0}s.
  236        * If the unsigned magnitude is zero, it is represented by a
  237        * single zero character {@code '0'}
  238        * (<code>'&#92;u0030'</code>); otherwise, the first character of
  239        * the representation of the unsigned magnitude will not be the
  240        * zero character. The characters {@code '0'}
  241        * (<code>'&#92;u0030'</code>) and {@code '1'}
  242        * (<code>'&#92;u0031'</code>) are used as binary digits.
  243        *
  244        * @param   i   an integer to be converted to a string.
  245        * @return  the string representation of the unsigned integer value
  246        *          represented by the argument in binary (base&nbsp;2).
  247        * @since   JDK1.0.2
  248        */
  249       public static String toBinaryString(int i) {
  250           return toUnsignedString(i, 1);
  251       }
  252   
  253       /**
  254        * Convert the integer to an unsigned number.
  255        */
  256       private static String toUnsignedString(int i, int shift) {
  257           char[] buf = new char[32];
  258           int charPos = 32;
  259           int radix = 1 << shift;
  260           int mask = radix - 1;
  261           do {
  262               buf[--charPos] = digits[i & mask];
  263               i >>>= shift;
  264           } while (i != 0);
  265   
  266           return new String(buf, charPos, (32 - charPos));
  267       }
  268   
  269   
  270       final static char [] DigitTens = {
  271           '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
  272           '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
  273           '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
  274           '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
  275           '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
  276           '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
  277           '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
  278           '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
  279           '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
  280           '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
  281           } ;
  282   
  283       final static char [] DigitOnes = {
  284           '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  285           '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  286           '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  287           '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  288           '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  289           '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  290           '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  291           '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  292           '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  293           '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  294           } ;
  295   
  296           // I use the "invariant division by multiplication" trick to
  297           // accelerate Integer.toString.  In particular we want to
  298           // avoid division by 10.
  299           //
  300           // The "trick" has roughly the same performance characteristics
  301           // as the "classic" Integer.toString code on a non-JIT VM.
  302           // The trick avoids .rem and .div calls but has a longer code
  303           // path and is thus dominated by dispatch overhead.  In the
  304           // JIT case the dispatch overhead doesn't exist and the
  305           // "trick" is considerably faster than the classic code.
  306           //
  307           // TODO-FIXME: convert (x * 52429) into the equiv shift-add
  308           // sequence.
  309           //
  310           // RE:  Division by Invariant Integers using Multiplication
  311           //      T Gralund, P Montgomery
  312           //      ACM PLDI 1994
  313           //
  314   
  315       /**
  316        * Returns a {@code String} object representing the
  317        * specified integer. The argument is converted to signed decimal
  318        * representation and returned as a string, exactly as if the
  319        * argument and radix 10 were given as arguments to the {@link
  320        * #toString(int, int)} method.
  321        *
  322        * @param   i   an integer to be converted.
  323        * @return  a string representation of the argument in base&nbsp;10.
  324        */
  325       public static String toString(int i) {
  326           if (i == Integer.MIN_VALUE)
  327               return "-2147483648";
  328           int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
  329           char[] buf = new char[size];
  330           getChars(i, size, buf);
  331           return new String(0, size, buf);
  332       }
  333   
  334       /**
  335        * Places characters representing the integer i into the
  336        * character array buf. The characters are placed into
  337        * the buffer backwards starting with the least significant
  338        * digit at the specified index (exclusive), and working
  339        * backwards from there.
  340        *
  341        * Will fail if i == Integer.MIN_VALUE
  342        */
  343       static void getChars(int i, int index, char[] buf) {
  344           int q, r;
  345           int charPos = index;
  346           char sign = 0;
  347   
  348           if (i < 0) {
  349               sign = '-';
  350               i = -i;
  351           }
  352   
  353           // Generate two digits per iteration
  354           while (i >= 65536) {
  355               q = i / 100;
  356           // really: r = i - (q * 100);
  357               r = i - ((q << 6) + (q << 5) + (q << 2));
  358               i = q;
  359               buf [--charPos] = DigitOnes[r];
  360               buf [--charPos] = DigitTens[r];
  361           }
  362   
  363           // Fall thru to fast mode for smaller numbers
  364           // assert(i <= 65536, i);
  365           for (;;) {
  366               q = (i * 52429) >>> (16+3);
  367               r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
  368               buf [--charPos] = digits [r];
  369               i = q;
  370               if (i == 0) break;
  371           }
  372           if (sign != 0) {
  373               buf [--charPos] = sign;
  374           }
  375       }
  376   
  377       final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
  378                                         99999999, 999999999, Integer.MAX_VALUE };
  379   
  380       // Requires positive x
  381       static int stringSize(int x) {
  382           for (int i=0; ; i++)
  383               if (x <= sizeTable[i])
  384                   return i+1;
  385       }
  386   
  387       /**
  388        * Parses the string argument as a signed integer in the radix
  389        * specified by the second argument. The characters in the string
  390        * must all be digits of the specified radix (as determined by
  391        * whether {@link java.lang.Character#digit(char, int)} returns a
  392        * nonnegative value), except that the first character may be an
  393        * ASCII minus sign {@code '-'} (<code>'&#92;u002D'</code>) to
  394        * indicate a negative value. The resulting integer value is
  395        * returned.
  396        *
  397        * <p>An exception of type {@code NumberFormatException} is
  398        * thrown if any of the following situations occurs:
  399        * <ul>
  400        * <li>The first argument is {@code null} or is a string of
  401        * length zero.
  402        *
  403        * <li>The radix is either smaller than
  404        * {@link java.lang.Character#MIN_RADIX} or
  405        * larger than {@link java.lang.Character#MAX_RADIX}.
  406        *
  407        * <li>Any character of the string is not a digit of the specified
  408        * radix, except that the first character may be a minus sign
  409        * {@code '-'} (<code>'&#92;u002D'</code>) provided that the
  410        * string is longer than length 1.
  411        *
  412        * <li>The value represented by the string is not a value of type
  413        * {@code int}.
  414        * </ul>
  415        *
  416        * <p>Examples:
  417        * <blockquote><pre>
  418        * parseInt("0", 10) returns 0
  419        * parseInt("473", 10) returns 473
  420        * parseInt("-0", 10) returns 0
  421        * parseInt("-FF", 16) returns -255
  422        * parseInt("1100110", 2) returns 102
  423        * parseInt("2147483647", 10) returns 2147483647
  424        * parseInt("-2147483648", 10) returns -2147483648
  425        * parseInt("2147483648", 10) throws a NumberFormatException
  426        * parseInt("99", 8) throws a NumberFormatException
  427        * parseInt("Kona", 10) throws a NumberFormatException
  428        * parseInt("Kona", 27) returns 411787
  429        * </pre></blockquote>
  430        *
  431        * @param      s   the {@code String} containing the integer
  432        *                  representation to be parsed
  433        * @param      radix   the radix to be used while parsing {@code s}.
  434        * @return     the integer represented by the string argument in the
  435        *             specified radix.
  436        * @exception  NumberFormatException if the {@code String}
  437        *             does not contain a parsable {@code int}.
  438        */
  439       public static int parseInt(String s, int radix)
  440                   throws NumberFormatException
  441       {
  442           if (s == null) {
  443               throw new NumberFormatException("null");
  444           }
  445   
  446           if (radix < Character.MIN_RADIX) {
  447               throw new NumberFormatException("radix " + radix +
  448                                               " less than Character.MIN_RADIX");
  449           }
  450   
  451           if (radix > Character.MAX_RADIX) {
  452               throw new NumberFormatException("radix " + radix +
  453                                               " greater than Character.MAX_RADIX");
  454           }
  455   
  456           int result = 0;
  457           boolean negative = false;
  458           int i = 0, len = s.length();
  459           int limit = -Integer.MAX_VALUE;
  460           int multmin;
  461           int digit;
  462   
  463           if (len > 0) {
  464               char firstChar = s.charAt(0);
  465               if (firstChar < '0') { // Possible leading "-"
  466                   if (firstChar == '-') {
  467                       negative = true;
  468                       limit = Integer.MIN_VALUE;
  469                   } else
  470                       throw NumberFormatException.forInputString(s);
  471   
  472                   if (len == 1) // Cannot have lone "-"
  473                       throw NumberFormatException.forInputString(s);
  474                   i++;
  475               }
  476               multmin = limit / radix;
  477               while (i < len) {
  478                   // Accumulating negatively avoids surprises near MAX_VALUE
  479                   digit = Character.digit(s.charAt(i++),radix);
  480                   if (digit < 0) {
  481                       throw NumberFormatException.forInputString(s);
  482                   }
  483                   if (result < multmin) {
  484                       throw NumberFormatException.forInputString(s);
  485                   }
  486                   result *= radix;
  487                   if (result < limit + digit) {
  488                       throw NumberFormatException.forInputString(s);
  489                   }
  490                   result -= digit;
  491               }
  492           } else {
  493               throw NumberFormatException.forInputString(s);
  494           }
  495           return negative ? result : -result;
  496       }
  497   
  498       /**
  499        * Parses the string argument as a signed decimal integer. The
  500        * characters in the string must all be decimal digits, except
  501        * that the first character may be an ASCII minus sign {@code '-'}
  502        * (<code>'&#92;u002D'</code>) to indicate a negative value.  The
  503        * resulting integer value is returned, exactly as if the argument
  504        * and the radix 10 were given as arguments to the {@link
  505        * #parseInt(java.lang.String, int)} method.
  506        *
  507        * @param s    a {@code String} containing the {@code int}
  508        *             representation to be parsed
  509        * @return     the integer value represented by the argument in decimal.
  510        * @exception  NumberFormatException  if the string does not contain a
  511        *               parsable integer.
  512        */
  513       public static int parseInt(String s) throws NumberFormatException {
  514           return parseInt(s,10);
  515       }
  516   
  517       /**
  518        * Returns an {@code Integer} object holding the value
  519        * extracted from the specified {@code String} when parsed
  520        * with the radix given by the second argument. The first argument
  521        * is interpreted as representing a signed integer in the radix
  522        * specified by the second argument, exactly as if the arguments
  523        * were given to the {@link #parseInt(java.lang.String, int)}
  524        * method. The result is an {@code Integer} object that
  525        * represents the integer value specified by the string.
  526        *
  527        * <p>In other words, this method returns an {@code Integer}
  528        * object equal to the value of:
  529        *
  530        * <blockquote>
  531        *  {@code new Integer(Integer.parseInt(s, radix))}
  532        * </blockquote>
  533        *
  534        * @param      s   the string to be parsed.
  535        * @param      radix the radix to be used in interpreting {@code s}
  536        * @return     an {@code Integer} object holding the value
  537        *             represented by the string argument in the specified
  538        *             radix.
  539        * @exception NumberFormatException if the {@code String}
  540        *            does not contain a parsable {@code int}.
  541        */
  542       public static Integer valueOf(String s, int radix) throws NumberFormatException {
  543           return new Integer(parseInt(s,radix));
  544       }
  545   
  546       /**
  547        * Returns an {@code Integer} object holding the
  548        * value of the specified {@code String}. The argument is
  549        * interpreted as representing a signed decimal integer, exactly
  550        * as if the argument were given to the {@link
  551        * #parseInt(java.lang.String)} method. The result is an
  552        * {@code Integer} object that represents the integer value
  553        * specified by the string.
  554        *
  555        * <p>In other words, this method returns an {@code Integer}
  556        * object equal to the value of:
  557        *
  558        * <blockquote>
  559        *  {@code new Integer(Integer.parseInt(s))}
  560        * </blockquote>
  561        *
  562        * @param      s   the string to be parsed.
  563        * @return     an {@code Integer} object holding the value
  564        *             represented by the string argument.
  565        * @exception  NumberFormatException  if the string cannot be parsed
  566        *             as an integer.
  567        */
  568       public static Integer valueOf(String s) throws NumberFormatException
  569       {
  570           return new Integer(parseInt(s, 10));
  571       }
  572   
  573       private static class IntegerCache {
  574           private IntegerCache(){}
  575   
  576           static final Integer cache[] = new Integer[-(-128) + 127 + 1];
  577   
  578           static {
  579               for(int i = 0; i < cache.length; i++)
  580                   cache[i] = new Integer(i - 128);
  581           }
  582       }
  583   
  584       /**
  585        * Returns an {@code Integer} instance representing the specified
  586        * {@code int} value.  If a new {@code Integer} instance is not
  587        * required, this method should generally be used in preference to
  588        * the constructor {@link #Integer(int)}, as this method is likely
  589        * to yield significantly better space and time performance by
  590        * caching frequently requested values.
  591        *
  592        * @param  i an {@code int} value.
  593        * @return an {@code Integer} instance representing {@code i}.
  594        * @since  1.5
  595        */
  596       public static Integer valueOf(int i) {
  597           final int offset = 128;
  598           if (i >= -128 && i <= 127) { // must cache
  599               return IntegerCache.cache[i + offset];
  600           }
  601           return new Integer(i);
  602       }
  603   
  604       /**
  605        * The value of the {@code Integer}.
  606        *
  607        * @serial
  608        */
  609       private final int value;
  610   
  611       /**
  612        * Constructs a newly allocated {@code Integer} object that
  613        * represents the specified {@code int} value.
  614        *
  615        * @param   value   the value to be represented by the
  616        *                  {@code Integer} object.
  617        */
  618       public Integer(int value) {
  619           this.value = value;
  620       }
  621   
  622       /**
  623        * Constructs a newly allocated {@code Integer} object that
  624        * represents the {@code int} value indicated by the
  625        * {@code String} parameter. The string is converted to an
  626        * {@code int} value in exactly the manner used by the
  627        * {@code parseInt} method for radix 10.
  628        *
  629        * @param      s   the {@code String} to be converted to an
  630        *                 {@code Integer}.
  631        * @exception  NumberFormatException  if the {@code String} does not
  632        *               contain a parsable integer.
  633        * @see        java.lang.Integer#parseInt(java.lang.String, int)
  634        */
  635       public Integer(String s) throws NumberFormatException {
  636           this.value = parseInt(s, 10);
  637       }
  638   
  639       /**
  640        * Returns the value of this {@code Integer} as a
  641        * {@code byte}.
  642        */
  643       public byte byteValue() {
  644           return (byte)value;
  645       }
  646   
  647       /**
  648        * Returns the value of this {@code Integer} as a
  649        * {@code short}.
  650        */
  651       public short shortValue() {
  652           return (short)value;
  653       }
  654   
  655       /**
  656        * Returns the value of this {@code Integer} as an
  657        * {@code int}.
  658        */
  659       public int intValue() {
  660           return value;
  661       }
  662   
  663       /**
  664        * Returns the value of this {@code Integer} as a
  665        * {@code long}.
  666        */
  667       public long longValue() {
  668           return (long)value;
  669       }
  670   
  671       /**
  672        * Returns the value of this {@code Integer} as a
  673        * {@code float}.
  674        */
  675       public float floatValue() {
  676           return (float)value;
  677       }
  678   
  679       /**
  680        * Returns the value of this {@code Integer} as a
  681        * {@code double}.
  682        */
  683       public double doubleValue() {
  684           return (double)value;
  685       }
  686   
  687       /**
  688        * Returns a {@code String} object representing this
  689        * {@code Integer}'s value. The value is converted to signed
  690        * decimal representation and returned as a string, exactly as if
  691        * the integer value were given as an argument to the {@link
  692        * java.lang.Integer#toString(int)} method.
  693        *
  694        * @return  a string representation of the value of this object in
  695        *          base&nbsp;10.
  696        */
  697       public String toString() {
  698           return String.valueOf(value);
  699       }
  700   
  701       /**
  702        * Returns a hash code for this {@code Integer}.
  703        *
  704        * @return  a hash code value for this object, equal to the
  705        *          primitive {@code int} value represented by this
  706        *          {@code Integer} object.
  707        */
  708       public int hashCode() {
  709           return value;
  710       }
  711   
  712       /**
  713        * Compares this object to the specified object.  The result is
  714        * {@code true} if and only if the argument is not
  715        * {@code null} and is an {@code Integer} object that
  716        * contains the same {@code int} value as this object.
  717        *
  718        * @param   obj   the object to compare with.
  719        * @return  {@code true} if the objects are the same;
  720        *          {@code false} otherwise.
  721        */
  722       public boolean equals(Object obj) {
  723           if (obj instanceof Integer) {
  724               return value == ((Integer)obj).intValue();
  725           }
  726           return false;
  727       }
  728   
  729       /**
  730        * Determines the integer value of the system property with the
  731        * specified name.
  732        *
  733        * <p>The first argument is treated as the name of a system property.
  734        * System properties are accessible through the
  735        * {@link java.lang.System#getProperty(java.lang.String)} method. The
  736        * string value of this property is then interpreted as an integer
  737        * value and an {@code Integer} object representing this value is
  738        * returned. Details of possible numeric formats can be found with
  739        * the definition of {@code getProperty}.
  740        *
  741        * <p>If there is no property with the specified name, if the specified name
  742        * is empty or {@code null}, or if the property does not have
  743        * the correct numeric format, then {@code null} is returned.
  744        *
  745        * <p>In other words, this method returns an {@code Integer}
  746        * object equal to the value of:
  747        *
  748        * <blockquote>
  749        *  {@code getInteger(nm, null)}
  750        * </blockquote>
  751        *
  752        * @param   nm   property name.
  753        * @return  the {@code Integer} value of the property.
  754        * @see     java.lang.System#getProperty(java.lang.String)
  755        * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
  756        */
  757       public static Integer getInteger(String nm) {
  758           return getInteger(nm, null);
  759       }
  760   
  761       /**
  762        * Determines the integer value of the system property with the
  763        * specified name.
  764        *
  765        * <p>The first argument is treated as the name of a system property.
  766        * System properties are accessible through the {@link
  767        * java.lang.System#getProperty(java.lang.String)} method. The
  768        * string value of this property is then interpreted as an integer
  769        * value and an {@code Integer} object representing this value is
  770        * returned. Details of possible numeric formats can be found with
  771        * the definition of {@code getProperty}.
  772        *
  773        * <p>The second argument is the default value. An {@code Integer} object
  774        * that represents the value of the second argument is returned if there
  775        * is no property of the specified name, if the property does not have
  776        * the correct numeric format, or if the specified name is empty or
  777        * {@code null}.
  778        *
  779        * <p>In other words, this method returns an {@code Integer} object
  780        * equal to the value of:
  781        *
  782        * <blockquote>
  783        *  {@code getInteger(nm, new Integer(val))}
  784        * </blockquote>
  785        *
  786        * but in practice it may be implemented in a manner such as:
  787        *
  788        * <blockquote><pre>
  789        * Integer result = getInteger(nm, null);
  790        * return (result == null) ? new Integer(val) : result;
  791        * </pre></blockquote>
  792        *
  793        * to avoid the unnecessary allocation of an {@code Integer}
  794        * object when the default value is not needed.
  795        *
  796        * @param   nm   property name.
  797        * @param   val   default value.
  798        * @return  the {@code Integer} value of the property.
  799        * @see     java.lang.System#getProperty(java.lang.String)
  800        * @see     java.lang.System#getProperty(java.lang.String, java.lang.String)
  801        */
  802       public static Integer getInteger(String nm, int val) {
  803           Integer result = getInteger(nm, null);
  804           return (result == null) ? new Integer(val) : result;
  805       }
  806   
  807       /**
  808        * Returns the integer value of the system property with the
  809        * specified name.  The first argument is treated as the name of a
  810        * system property.  System properties are accessible through the
  811        * {@link java.lang.System#getProperty(java.lang.String)} method.
  812        * The string value of this property is then interpreted as an
  813        * integer value, as per the {@code Integer.decode} method,
  814        * and an {@code Integer} object representing this value is
  815        * returned.
  816        *
  817        * <ul><li>If the property value begins with the two ASCII characters
  818        *         {@code 0x} or the ASCII character {@code #}, not
  819        *      followed by a minus sign, then the rest of it is parsed as a
  820        *      hexadecimal integer exactly as by the method
  821        *      {@link #valueOf(java.lang.String, int)} with radix 16.
  822        * <li>If the property value begins with the ASCII character
  823        *     {@code 0} followed by another character, it is parsed as an
  824        *     octal integer exactly as by the method
  825        *     {@link #valueOf(java.lang.String, int)} with radix 8.
  826        * <li>Otherwise, the property value is parsed as a decimal integer
  827        * exactly as by the method {@link #valueOf(java.lang.String, int)}
  828        * with radix 10.
  829        * </ul>
  830        *
  831        * <p>The second argument is the default value. The default value is
  832        * returned if there is no property of the specified name, if the
  833        * property does not have the correct numeric format, or if the
  834        * specified name is empty or {@code null}.
  835        *
  836        * @param   nm   property name.
  837        * @param   val   default value.
  838        * @return  the {@code Integer} value of the property.
  839        * @see     java.lang.System#getProperty(java.lang.String)
  840        * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
  841        * @see java.lang.Integer#decode
  842        */
  843       public static Integer getInteger(String nm, Integer val) {
  844           String v = null;
  845           try {
  846               v = System.getProperty(nm);
  847           } catch (IllegalArgumentException e) {
  848           } catch (NullPointerException e) {
  849           }
  850           if (v != null) {
  851               try {
  852                   return Integer.decode(v);
  853               } catch (NumberFormatException e) {
  854               }
  855           }
  856           return val;
  857       }
  858   
  859       /**
  860        * Decodes a {@code String} into an {@code Integer}.
  861        * Accepts decimal, hexadecimal, and octal numbers given
  862        * by the following grammar:
  863        *
  864        * <blockquote>
  865        * <dl>
  866        * <dt><i>DecodableString:</i>
  867        * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
  868        * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
  869        * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
  870        * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
  871        * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
  872        * <p>
  873        * <dt><i>Sign:</i>
  874        * <dd>{@code -}
  875        * </dl>
  876        * </blockquote>
  877        *
  878        * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
  879        * are defined in <a href="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48282">&sect;3.10.1</a>
  880        * of the <a href="http://java.sun.com/docs/books/jls/html/">Java
  881        * Language Specification</a>.
  882        *
  883        * <p>The sequence of characters following an (optional) negative
  884        * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
  885        * "{@code #}", or leading zero) is parsed as by the {@code
  886        * Integer.parseInt} method with the indicated radix (10, 16, or
  887        * 8).  This sequence of characters must represent a positive
  888        * value or a {@link NumberFormatException} will be thrown.  The
  889        * result is negated if first character of the specified {@code
  890        * String} is the minus sign.  No whitespace characters are
  891        * permitted in the {@code String}.
  892        *
  893        * @param     nm the {@code String} to decode.
  894        * @return    an {@code Integer} object holding the {@code int}
  895        *             value represented by {@code nm}
  896        * @exception NumberFormatException  if the {@code String} does not
  897        *            contain a parsable integer.
  898        * @see java.lang.Integer#parseInt(java.lang.String, int)
  899        */
  900       public static Integer decode(String nm) throws NumberFormatException {
  901           int radix = 10;
  902           int index = 0;
  903           boolean negative = false;
  904           Integer result;
  905   
  906           if (nm.length() == 0)
  907               throw new NumberFormatException("Zero length string");
  908           char firstChar = nm.charAt(0);
  909           // Handle sign, if present
  910           if (firstChar == '-') {
  911               negative = true;
  912               index++;
  913           }
  914   
  915           // Handle radix specifier, if present
  916           if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
  917               index += 2;
  918               radix = 16;
  919           }
  920           else if (nm.startsWith("#", index)) {
  921               index ++;
  922               radix = 16;
  923           }
  924           else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
  925               index ++;
  926               radix = 8;
  927           }
  928   
  929           if (nm.startsWith("-", index))
  930               throw new NumberFormatException("Sign character in wrong position");
  931   
  932           try {
  933               result = Integer.valueOf(nm.substring(index), radix);
  934               result = negative ? new Integer(-result.intValue()) : result;
  935           } catch (NumberFormatException e) {
  936               // If number is Integer.MIN_VALUE, we'll end up here. The next line
  937               // handles this case, and causes any genuine format error to be
  938               // rethrown.
  939               String constant = negative ? ("-" + nm.substring(index))
  940                                          : nm.substring(index);
  941               result = Integer.valueOf(constant, radix);
  942           }
  943           return result;
  944       }
  945   
  946       /**
  947        * Compares two {@code Integer} objects numerically.
  948        *
  949        * @param   anotherInteger   the {@code Integer} to be compared.
  950        * @return  the value {@code 0} if this {@code Integer} is
  951        *          equal to the argument {@code Integer}; a value less than
  952        *          {@code 0} if this {@code Integer} is numerically less
  953        *          than the argument {@code Integer}; and a value greater
  954        *          than {@code 0} if this {@code Integer} is numerically
  955        *           greater than the argument {@code Integer} (signed
  956        *           comparison).
  957        * @since   1.2
  958        */
  959       public int compareTo(Integer anotherInteger) {
  960           int thisVal = this.value;
  961           int anotherVal = anotherInteger.value;
  962           return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
  963       }
  964   
  965   
  966       // Bit twiddling
  967   
  968       /**
  969        * The number of bits used to represent an {@code int} value in two's
  970        * complement binary form.
  971        *
  972        * @since 1.5
  973        */
  974       public static final int SIZE = 32;
  975   
  976       /**
  977        * Returns an {@code int} value with at most a single one-bit, in the
  978        * position of the highest-order ("leftmost") one-bit in the specified
  979        * {@code int} value.  Returns zero if the specified value has no
  980        * one-bits in its two's complement binary representation, that is, if it
  981        * is equal to zero.
  982        *
  983        * @return an {@code int} value with a single one-bit, in the position
  984        *     of the highest-order one-bit in the specified value, or zero if
  985        *     the specified value is itself equal to zero.
  986        * @since 1.5
  987        */
  988       public static int highestOneBit(int i) {
  989           // HD, Figure 3-1
  990           i |= (i >>  1);
  991           i |= (i >>  2);
  992           i |= (i >>  4);
  993           i |= (i >>  8);
  994           i |= (i >> 16);
  995           return i - (i >>> 1);
  996       }
  997   
  998       /**
  999        * Returns an {@code int} value with at most a single one-bit, in the
 1000        * position of the lowest-order ("rightmost") one-bit in the specified
 1001        * {@code int} value.  Returns zero if the specified value has no
 1002        * one-bits in its two's complement binary representation, that is, if it
 1003        * is equal to zero.
 1004        *
 1005        * @return an {@code int} value with a single one-bit, in the position
 1006        *     of the lowest-order one-bit in the specified value, or zero if
 1007        *     the specified value is itself equal to zero.
 1008        * @since 1.5
 1009        */
 1010       public static int lowestOneBit(int i) {
 1011           // HD, Section 2-1
 1012           return i & -i;
 1013       }
 1014   
 1015       /**
 1016        * Returns the number of zero bits preceding the highest-order
 1017        * ("leftmost") one-bit in the two's complement binary representation
 1018        * of the specified {@code int} value.  Returns 32 if the
 1019        * specified value has no one-bits in its two's complement representation,
 1020        * in other words if it is equal to zero.
 1021        *
 1022        * <p>Note that this method is closely related to the logarithm base 2.
 1023        * For all positive {@code int} values x:
 1024        * <ul>
 1025        * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}
 1026        * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}
 1027        * </ul>
 1028        *
 1029        * @return the number of zero bits preceding the highest-order
 1030        *     ("leftmost") one-bit in the two's complement binary representation
 1031        *     of the specified {@code int} value, or 32 if the value
 1032        *     is equal to zero.
 1033        * @since 1.5
 1034        */
 1035       public static int numberOfLeadingZeros(int i) {
 1036           // HD, Figure 5-6
 1037           if (i == 0)
 1038               return 32;
 1039           int n = 1;
 1040           if (i >>> 16 == 0) { n += 16; i <<= 16; }
 1041           if (i >>> 24 == 0) { n +=  8; i <<=  8; }
 1042           if (i >>> 28 == 0) { n +=  4; i <<=  4; }
 1043           if (i >>> 30 == 0) { n +=  2; i <<=  2; }
 1044           n -= i >>> 31;
 1045           return n;
 1046       }
 1047   
 1048       /**
 1049        * Returns the number of zero bits following the lowest-order ("rightmost")
 1050        * one-bit in the two's complement binary representation of the specified
 1051        * {@code int} value.  Returns 32 if the specified value has no
 1052        * one-bits in its two's complement representation, in other words if it is
 1053        * equal to zero.
 1054        *
 1055        * @return the number of zero bits following the lowest-order ("rightmost")
 1056        *     one-bit in the two's complement binary representation of the
 1057        *     specified {@code int} value, or 32 if the value is equal
 1058        *     to zero.
 1059        * @since 1.5
 1060        */
 1061       public static int numberOfTrailingZeros(int i) {
 1062           // HD, Figure 5-14
 1063           int y;
 1064           if (i == 0) return 32;
 1065           int n = 31;
 1066           y = i <<16; if (y != 0) { n = n -16; i = y; }
 1067           y = i << 8; if (y != 0) { n = n - 8; i = y; }
 1068           y = i << 4; if (y != 0) { n = n - 4; i = y; }
 1069           y = i << 2; if (y != 0) { n = n - 2; i = y; }
 1070           return n - ((i << 1) >>> 31);
 1071       }
 1072   
 1073       /**
 1074        * Returns the number of one-bits in the two's complement binary
 1075        * representation of the specified {@code int} value.  This function is
 1076        * sometimes referred to as the <i>population count</i>.
 1077        *
 1078        * @return the number of one-bits in the two's complement binary
 1079        *     representation of the specified {@code int} value.
 1080        * @since 1.5
 1081        */
 1082       public static int bitCount(int i) {
 1083           // HD, Figure 5-2
 1084           i = i - ((i >>> 1) & 0x55555555);
 1085           i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
 1086           i = (i + (i >>> 4)) & 0x0f0f0f0f;
 1087           i = i + (i >>> 8);
 1088           i = i + (i >>> 16);
 1089           return i & 0x3f;
 1090       }
 1091   
 1092       /**
 1093        * Returns the value obtained by rotating the two's complement binary
 1094        * representation of the specified {@code int} value left by the
 1095        * specified number of bits.  (Bits shifted out of the left hand, or
 1096        * high-order, side reenter on the right, or low-order.)
 1097        *
 1098        * <p>Note that left rotation with a negative distance is equivalent to
 1099        * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
 1100        * distance)}.  Note also that rotation by any multiple of 32 is a
 1101        * no-op, so all but the last five bits of the rotation distance can be
 1102        * ignored, even if the distance is negative: {@code rotateLeft(val,
 1103        * distance) == rotateLeft(val, distance & 0x1F)}.
 1104        *
 1105        * @return the value obtained by rotating the two's complement binary
 1106        *     representation of the specified {@code int} value left by the
 1107        *     specified number of bits.
 1108        * @since 1.5
 1109        */
 1110       public static int rotateLeft(int i, int distance) {
 1111           return (i << distance) | (i >>> -distance);
 1112       }
 1113   
 1114       /**
 1115        * Returns the value obtained by rotating the two's complement binary
 1116        * representation of the specified {@code int} value right by the
 1117        * specified number of bits.  (Bits shifted out of the right hand, or
 1118        * low-order, side reenter on the left, or high-order.)
 1119        *
 1120        * <p>Note that right rotation with a negative distance is equivalent to
 1121        * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
 1122        * distance)}.  Note also that rotation by any multiple of 32 is a
 1123        * no-op, so all but the last five bits of the rotation distance can be
 1124        * ignored, even if the distance is negative: {@code rotateRight(val,
 1125        * distance) == rotateRight(val, distance & 0x1F)}.
 1126        *
 1127        * @return the value obtained by rotating the two's complement binary
 1128        *     representation of the specified {@code int} value right by the
 1129        *     specified number of bits.
 1130        * @since 1.5
 1131        */
 1132       public static int rotateRight(int i, int distance) {
 1133           return (i >>> distance) | (i << -distance);
 1134       }
 1135   
 1136       /**
 1137        * Returns the value obtained by reversing the order of the bits in the
 1138        * two's complement binary representation of the specified {@code int}
 1139        * value.
 1140        *
 1141        * @return the value obtained by reversing order of the bits in the
 1142        *     specified {@code int} value.
 1143        * @since 1.5
 1144        */
 1145       public static int reverse(int i) {
 1146           // HD, Figure 7-1
 1147           i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
 1148           i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
 1149           i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
 1150           i = (i << 24) | ((i & 0xff00) << 8) |
 1151               ((i >>> 8) & 0xff00) | (i >>> 24);
 1152           return i;
 1153       }
 1154   
 1155       /**
 1156        * Returns the signum function of the specified {@code int} value.  (The
 1157        * return value is -1 if the specified value is negative; 0 if the
 1158        * specified value is zero; and 1 if the specified value is positive.)
 1159        *
 1160        * @return the signum function of the specified {@code int} value.
 1161        * @since 1.5
 1162        */
 1163       public static int signum(int i) {
 1164           // HD, Section 2-7
 1165           return (i >> 31) | (-i >>> 31);
 1166       }
 1167   
 1168       /**
 1169        * Returns the value obtained by reversing the order of the bytes in the
 1170        * two's complement representation of the specified {@code int} value.
 1171        *
 1172        * @return the value obtained by reversing the bytes in the specified
 1173        *     {@code int} value.
 1174        * @since 1.5
 1175        */
 1176       public static int reverseBytes(int i) {
 1177           return ((i >>> 24)           ) |
 1178                  ((i >>   8) &   0xFF00) |
 1179                  ((i <<   8) & 0xFF0000) |
 1180                  ((i << 24));
 1181       }
 1182   
 1183       /** use serialVersionUID from JDK 1.0.2 for interoperability */
 1184       private static final long serialVersionUID = 1360826667806852920L;
 1185   }

Save This Page
Home » Open-JDK-6.b17-src » java » lang » [javadoc | source]