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