KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > lang > Integer


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
8 package java.lang;
9
10 /**
11  * The <code>Integer</code> class wraps a value of the primitive type
12  * <code>int</code> in an object. An object of type
13  * <code>Integer</code> contains a single field whose type is
14  * <code>int</code>.
15  *
16  * <p>
17  *
18  * In addition, this class provides several methods for converting an
19  * <code>int</code> to a <code>String</code> and a <code>String</code>
20  * to an <code>int</code>, as well as other constants and methods
21  * useful when dealing with an <code>int</code>.
22  *
23  * <p>Implementation note: The implementations of the "bit twiddling"
24  * methods (such as {@link #highestOneBit(int) highestOneBit} and
25  * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are
26  * based on material from Henry S. Warren, Jr.'s <i>Hacker's
27  * Delight</i>, (Addison Wesley, 2002).
28  *
29  * @author Lee Boynton
30  * @author Arthur van Hoff
31  * @author Josh Bloch
32  * @version 1.90, 05/11/04
33  * @since JDK1.0
34  */

35 public final class Integer extends Number JavaDoc implements Comparable JavaDoc<Integer JavaDoc> {
36     /**
37      * A constant holding the minimum value an <code>int</code> can
38      * have, -2<sup>31</sup>.
39      */

40     public static final int MIN_VALUE = 0x80000000;
41
42     /**
43      * A constant holding the maximum value an <code>int</code> can
44      * have, 2<sup>31</sup>-1.
45      */

46     public static final int MAX_VALUE = 0x7fffffff;
47
48     /**
49      * The <code>Class</code> instance representing the primitive type
50      * <code>int</code>.
51      *
52      * @since JDK1.1
53      */

54     public static final Class JavaDoc<Integer JavaDoc> TYPE = (Class JavaDoc<Integer JavaDoc>) Class.getPrimitiveClass("int");
55
56     /**
57      * All possible chars for representing a number as a String
58      */

59     final static char[] digits = {
60     '0' , '1' , '2' , '3' , '4' , '5' ,
61     '6' , '7' , '8' , '9' , 'a' , 'b' ,
62     'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
63     'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
64     'o' , 'p' , 'q' , 'r' , 's' , 't' ,
65     'u' , 'v' , 'w' , 'x' , 'y' , 'z'
66     };
67
68     /**
69      * Returns a string representation of the first argument in the
70      * radix specified by the second argument.
71      * <p>
72      * If the radix is smaller than <code>Character.MIN_RADIX</code>
73      * or larger than <code>Character.MAX_RADIX</code>, then the radix
74      * <code>10</code> is used instead.
75      * <p>
76      * If the first argument is negative, the first element of the
77      * result is the ASCII minus character <code>'-'</code>
78      * (<code>'&#92;u002D'</code>). If the first argument is not
79      * negative, no sign character appears in the result.
80      * <p>
81      * The remaining characters of the result represent the magnitude
82      * of the first argument. If the magnitude is zero, it is
83      * represented by a single zero character <code>'0'</code>
84      * (<code>'&#92;u0030'</code>); otherwise, the first character of
85      * the representation of the magnitude will not be the zero
86      * character. The following ASCII characters are used as digits:
87      * <blockquote><pre>
88      * 0123456789abcdefghijklmnopqrstuvwxyz
89      * </pre></blockquote>
90      * These are <code>'&#92;u0030'</code> through
91      * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through
92      * <code>'&#92;u007A'</code>. If <code>radix</code> is
93      * <var>N</var>, then the first <var>N</var> of these characters
94      * are used as radix-<var>N</var> digits in the order shown. Thus,
95      * the digits for hexadecimal (radix 16) are
96      * <code>0123456789abcdef</code>. If uppercase letters are
97      * desired, the {@link java.lang.String#toUpperCase()} method may
98      * be called on the result:
99      * <blockquote><pre>
100      * Integer.toString(n, 16).toUpperCase()
101      * </pre></blockquote>
102      *
103      * @param i an integer to be converted to a string.
104      * @param radix the radix to use in the string representation.
105      * @return a string representation of the argument in the specified radix.
106      * @see java.lang.Character#MAX_RADIX
107      * @see java.lang.Character#MIN_RADIX
108      */

109     public static String JavaDoc toString(int i, int radix) {
110
111         if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
112         radix = 10;
113
114     /* Use the faster version */
115     if (radix == 10) {
116         return toString(i);
117     }
118
119     char buf[] = new char[33];
120     boolean negative = (i < 0);
121     int charPos = 32;
122
123     if (!negative) {
124         i = -i;
125     }
126
127     while (i <= -radix) {
128         buf[charPos--] = digits[-(i % radix)];
129         i = i / radix;
130     }
131     buf[charPos] = digits[-i];
132
133     if (negative) {
134         buf[--charPos] = '-';
135     }
136
137     return new String JavaDoc(buf, charPos, (33 - charPos));
138     }
139
140     /**
141      * Returns a string representation of the integer argument as an
142      * unsigned integer in base&nbsp;16.
143      * <p>
144      * The unsigned integer value is the argument plus 2<sup>32</sup>
145      * if the argument is negative; otherwise, it is equal to the
146      * argument. This value is converted to a string of ASCII digits
147      * in hexadecimal (base&nbsp;16) with no extra leading
148      * <code>0</code>s. If the unsigned magnitude is zero, it is
149      * represented by a single zero character <code>'0'</code>
150      * (<code>'&#92;u0030'</code>); otherwise, the first character of
151      * the representation of the unsigned magnitude will not be the
152      * zero character. The following characters are used as
153      * hexadecimal digits:
154      * <blockquote><pre>
155      * 0123456789abcdef
156      * </pre></blockquote>
157      * These are the characters <code>'&#92;u0030'</code> through
158      * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through
159      * <code>'&#92;u0066'</code>. If uppercase letters are
160      * desired, the {@link java.lang.String#toUpperCase()} method may
161      * be called on the result:
162      * <blockquote><pre>
163      * Integer.toHexString(n).toUpperCase()
164      * </pre></blockquote>
165      *
166      * @param i an integer to be converted to a string.
167      * @return the string representation of the unsigned integer value
168      * represented by the argument in hexadecimal (base&nbsp;16).
169      * @since JDK1.0.2
170      */

171     public static String JavaDoc toHexString(int i) {
172     return toUnsignedString(i, 4);
173     }
174
175     /**
176      * Returns a string representation of the integer argument as an
177      * unsigned integer in base&nbsp;8.
178      * <p>
179      * The unsigned integer value is the argument plus 2<sup>32</sup>
180      * if the argument is negative; otherwise, it is equal to the
181      * argument. This value is converted to a string of ASCII digits
182      * in octal (base&nbsp;8) with no extra leading <code>0</code>s.
183      * <p>
184      * If the unsigned magnitude is zero, it is represented by a
185      * single zero character <code>'0'</code>
186      * (<code>'&#92;u0030'</code>); otherwise, the first character of
187      * the representation of the unsigned magnitude will not be the
188      * zero character. The following characters are used as octal
189      * digits:
190      * <blockquote><pre>
191      * 01234567
192      * </pre></blockquote>
193      * These are the characters <code>'&#92;u0030'</code> through
194      * <code>'&#92;u0037'</code>.
195      *
196      * @param i an integer to be converted to a string.
197      * @return the string representation of the unsigned integer value
198      * represented by the argument in octal (base&nbsp;8).
199      * @since JDK1.0.2
200      */

201     public static String JavaDoc toOctalString(int i) {
202     return toUnsignedString(i, 3);
203     }
204
205     /**
206      * Returns a string representation of the integer argument as an
207      * unsigned integer in base&nbsp;2.
208      * <p>
209      * The unsigned integer value is the argument plus 2<sup>32</sup>
210      * if the argument is negative; otherwise it is equal to the
211      * argument. This value is converted to a string of ASCII digits
212      * in binary (base&nbsp;2) with no extra leading <code>0</code>s.
213      * If the unsigned magnitude is zero, it is represented by a
214      * single zero character <code>'0'</code>
215      * (<code>'&#92;u0030'</code>); otherwise, the first character of
216      * the representation of the unsigned magnitude will not be the
217      * zero character. The characters <code>'0'</code>
218      * (<code>'&#92;u0030'</code>) and <code>'1'</code>
219      * (<code>'&#92;u0031'</code>) are used as binary digits.
220      *
221      * @param i an integer to be converted to a string.
222      * @return the string representation of the unsigned integer value
223      * represented by the argument in binary (base&nbsp;2).
224      * @since JDK1.0.2
225      */

226     public static String JavaDoc toBinaryString(int i) {
227     return toUnsignedString(i, 1);
228     }
229
230     /**
231      * Convert the integer to an unsigned number.
232      */

233     private static String JavaDoc toUnsignedString(int i, int shift) {
234     char[] buf = new char[32];
235     int charPos = 32;
236     int radix = 1 << shift;
237     int mask = radix - 1;
238     do {
239         buf[--charPos] = digits[i & mask];
240         i >>>= shift;
241     } while (i != 0);
242
243     return new String JavaDoc(buf, charPos, (32 - charPos));
244     }
245
246
247     final static char [] DigitTens = {
248     '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
249     '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
250     '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
251     '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
252     '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
253     '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
254     '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
255     '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
256     '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
257     '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
258     } ;
259
260     final static char [] DigitOnes = {
261     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
262     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
263     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
264     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
265     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
266     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
267     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
268     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
269     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
270     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
271     } ;
272
273     // I use the "invariant division by multiplication" trick to
274
// accelerate Integer.toString. In particular we want to
275
// avoid division by 10.
276
//
277
// The "trick" has roughly the same performance characteristics
278
// as the "classic" Integer.toString code on a non-JIT VM.
279
// The trick avoids .rem and .div calls but has a longer code
280
// path and is thus dominated by dispatch overhead. In the
281
// JIT case the dispatch overhead doesn't exist and the
282
// "trick" is considerably faster than the classic code.
283
//
284
// TODO-FIXME: convert (x * 52429) into the equiv shift-add
285
// sequence.
286
//
287
// RE: Division by Invariant Integers using Multiplication
288
// T Gralund, P Montgomery
289
// ACM PLDI 1994
290
//
291

292     /**
293      * Returns a <code>String</code> object representing the
294      * specified integer. The argument is converted to signed decimal
295      * representation and returned as a string, exactly as if the
296      * argument and radix 10 were given as arguments to the {@link
297      * #toString(int, int)} method.
298      *
299      * @param i an integer to be converted.
300      * @return a string representation of the argument in base&nbsp;10.
301      */

302     public static String JavaDoc toString(int i) {
303         if (i == Integer.MIN_VALUE)
304             return "-2147483648";
305         int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
306         char[] buf = new char[size];
307         getChars(i, size, buf);
308         return new String JavaDoc(0, size, buf);
309     }
310
311     /**
312      * Places characters representing the integer i into the
313      * character array buf. The characters are placed into
314      * the buffer backwards starting with the least significant
315      * digit at the specified index (exclusive), and working
316      * backwards from there.
317      *
318      * Will fail if i == Integer.MIN_VALUE
319      */

320     static void getChars(int i, int index, char[] buf) {
321         int q, r;
322         int charPos = index;
323         char sign = 0;
324
325         if (i < 0) {
326             sign = '-';
327             i = -i;
328         }
329
330         // Generate two digits per iteration
331
while (i >= 65536) {
332             q = i / 100;
333         // really: r = i - (q * 100);
334
r = i - ((q << 6) + (q << 5) + (q << 2));
335             i = q;
336             buf [--charPos] = DigitOnes[r];
337             buf [--charPos] = DigitTens[r];
338         }
339
340         // Fall thru to fast mode for smaller numbers
341
// assert(i <= 65536, i);
342
for (;;) {
343             q = (i * 52429) >>> (16+3);
344             r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...
345
buf [--charPos] = digits [r];
346             i = q;
347             if (i == 0) break;
348         }
349         if (sign != 0) {
350             buf [--charPos] = sign;
351         }
352     }
353
354     final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
355                                       99999999, 999999999, Integer.MAX_VALUE };
356
357     // Requires positive x
358
static int stringSize(int x) {
359         for (int i=0; ; i++)
360             if (x <= sizeTable[i])
361                 return i+1;
362     }
363     
364     /**
365      * Parses the string argument as a signed integer in the radix
366      * specified by the second argument. The characters in the string
367      * must all be digits of the specified radix (as determined by
368      * whether {@link java.lang.Character#digit(char, int)} returns a
369      * nonnegative value), except that the first character may be an
370      * ASCII minus sign <code>'-'</code> (<code>'&#92;u002D'</code>) to
371      * indicate a negative value. The resulting integer value is returned.
372      * <p>
373      * An exception of type <code>NumberFormatException</code> is
374      * thrown if any of the following situations occurs:
375      * <ul>
376      * <li>The first argument is <code>null</code> or is a string of
377      * length zero.
378      * <li>The radix is either smaller than
379      * {@link java.lang.Character#MIN_RADIX} or
380      * larger than {@link java.lang.Character#MAX_RADIX}.
381      * <li>Any character of the string is not a digit of the specified
382      * radix, except that the first character may be a minus sign
383      * <code>'-'</code> (<code>'&#92;u002D'</code>) provided that the
384      * string is longer than length 1.
385      * <li>The value represented by the string is not a value of type
386      * <code>int</code>.
387      * </ul><p>
388      * Examples:
389      * <blockquote><pre>
390      * parseInt("0", 10) returns 0
391      * parseInt("473", 10) returns 473
392      * parseInt("-0", 10) returns 0
393      * parseInt("-FF", 16) returns -255
394      * parseInt("1100110", 2) returns 102
395      * parseInt("2147483647", 10) returns 2147483647
396      * parseInt("-2147483648", 10) returns -2147483648
397      * parseInt("2147483648", 10) throws a NumberFormatException
398      * parseInt("99", 8) throws a NumberFormatException
399      * parseInt("Kona", 10) throws a NumberFormatException
400      * parseInt("Kona", 27) returns 411787
401      * </pre></blockquote>
402      *
403      * @param s the <code>String</code> containing the integer
404      * representation to be parsed
405      * @param radix the radix to be used while parsing <code>s</code>.
406      * @return the integer represented by the string argument in the
407      * specified radix.
408      * @exception NumberFormatException if the <code>String</code>
409      * does not contain a parsable <code>int</code>.
410      */

411     public static int parseInt(String JavaDoc s, int radix)
412         throws NumberFormatException JavaDoc
413     {
414         if (s == null) {
415             throw new NumberFormatException JavaDoc("null");
416         }
417
418     if (radix < Character.MIN_RADIX) {
419         throw new NumberFormatException JavaDoc("radix " + radix +
420                         " less than Character.MIN_RADIX");
421     }
422
423     if (radix > Character.MAX_RADIX) {
424         throw new NumberFormatException JavaDoc("radix " + radix +
425                         " greater than Character.MAX_RADIX");
426     }
427
428     int result = 0;
429     boolean negative = false;
430     int i = 0, max = s.length();
431     int limit;
432     int multmin;
433     int digit;
434
435     if (max > 0) {
436         if (s.charAt(0) == '-') {
437         negative = true;
438         limit = Integer.MIN_VALUE;
439         i++;
440         } else {
441         limit = -Integer.MAX_VALUE;
442         }
443         multmin = limit / radix;
444         if (i < max) {
445         digit = Character.digit(s.charAt(i++),radix);
446         if (digit < 0) {
447             throw NumberFormatException.forInputString(s);
448         } else {
449             result = -digit;
450         }
451         }
452         while (i < max) {
453         // Accumulating negatively avoids surprises near MAX_VALUE
454
digit = Character.digit(s.charAt(i++),radix);
455         if (digit < 0) {
456             throw NumberFormatException.forInputString(s);
457         }
458         if (result < multmin) {
459             throw NumberFormatException.forInputString(s);
460         }
461         result *= radix;
462         if (result < limit + digit) {
463             throw NumberFormatException.forInputString(s);
464         }
465         result -= digit;
466         }
467     } else {
468         throw NumberFormatException.forInputString(s);
469     }
470     if (negative) {
471         if (i > 1) {
472         return result;
473         } else { /* Only got "-" */
474         throw NumberFormatException.forInputString(s);
475         }
476     } else {
477         return -result;
478     }
479     }
480
481     /**
482      * Parses the string argument as a signed decimal integer. The
483      * characters in the string must all be decimal digits, except that
484      * the first character may be an ASCII minus sign <code>'-'</code>
485      * (<code>'&#92;u002D'</code>) to indicate a negative value. The resulting
486      * integer value is returned, exactly as if the argument and the radix
487      * 10 were given as arguments to the
488      * {@link #parseInt(java.lang.String, int)} method.
489      *
490      * @param s a <code>String</code> containing the <code>int</code>
491      * representation to be parsed
492      * @return the integer value represented by the argument in decimal.
493      * @exception NumberFormatException if the string does not contain a
494      * parsable integer.
495      */

496     public static int parseInt(String JavaDoc s) throws NumberFormatException JavaDoc {
497     return parseInt(s,10);
498     }
499
500     /**
501      * Returns an <code>Integer</code> object holding the value
502      * extracted from the specified <code>String</code> when parsed
503      * with the radix given by the second argument. The first argument
504      * is interpreted as representing a signed integer in the radix
505      * specified by the second argument, exactly as if the arguments
506      * were given to the {@link #parseInt(java.lang.String, int)}
507      * method. The result is an <code>Integer</code> object that
508      * represents the integer value specified by the string.
509      * <p>
510      * In other words, this method returns an <code>Integer</code>
511      * object equal to the value of:
512      *
513      * <blockquote><code>
514      * new Integer(Integer.parseInt(s, radix))
515      * </code></blockquote>
516      *
517      * @param s the string to be parsed.
518      * @param radix the radix to be used in interpreting <code>s</code>
519      * @return an <code>Integer</code> object holding the value
520      * represented by the string argument in the specified
521      * radix.
522      * @exception NumberFormatException if the <code>String</code>
523      * does not contain a parsable <code>int</code>.
524      */

525     public static Integer JavaDoc valueOf(String JavaDoc s, int radix) throws NumberFormatException JavaDoc {
526     return new Integer JavaDoc(parseInt(s,radix));
527     }
528
529     /**
530      * Returns an <code>Integer</code> object holding the
531      * value of the specified <code>String</code>. The argument is
532      * interpreted as representing a signed decimal integer, exactly
533      * as if the argument were given to the {@link
534      * #parseInt(java.lang.String)} method. The result is an
535      * <code>Integer</code> object that represents the integer value
536      * specified by the string.
537      * <p>
538      * In other words, this method returns an <code>Integer</code>
539      * object equal to the value of:
540      *
541      * <blockquote><code>
542      * new Integer(Integer.parseInt(s))
543      * </code></blockquote>
544      *
545      * @param s the string to be parsed.
546      * @return an <code>Integer</code> object holding the value
547      * represented by the string argument.
548      * @exception NumberFormatException if the string cannot be parsed
549      * as an integer.
550      */

551     public static Integer JavaDoc valueOf(String JavaDoc s) throws NumberFormatException JavaDoc
552     {
553     return new Integer JavaDoc(parseInt(s, 10));
554     }
555
556     private static class IntegerCache {
557     private IntegerCache(){}
558
559     static final Integer JavaDoc cache[] = new Integer JavaDoc[-(-128) + 127 + 1];
560
561     static {
562         for(int i = 0; i < cache.length; i++)
563         cache[i] = new Integer JavaDoc(i - 128);
564     }
565     }
566
567     /**
568      * Returns a <tt>Integer</tt> instance representing the specified
569      * <tt>int</tt> value.
570      * If a new <tt>Integer</tt> instance is not required, this method
571      * should generally be used in preference to the constructor
572      * {@link #Integer(int)}, as this method is likely to yield
573      * significantly better space and time performance by caching
574      * frequently requested values.
575      *
576      * @param i an <code>int</code> value.
577      * @return a <tt>Integer</tt> instance representing <tt>i</tt>.
578      * @since 1.5
579      */

580     public static Integer JavaDoc valueOf(int i) {
581     final int offset = 128;
582     if (i >= -128 && i <= 127) { // must cache
583
return IntegerCache.cache[i + offset];
584     }
585         return new Integer JavaDoc(i);
586     }
587
588     /**
589      * The value of the <code>Integer</code>.
590      *
591      * @serial
592      */

593     private final int value;
594
595     /**
596      * Constructs a newly allocated <code>Integer</code> object that
597      * represents the specified <code>int</code> value.
598      *
599      * @param value the value to be represented by the
600      * <code>Integer</code> object.
601      */

602     public Integer(int value) {
603     this.value = value;
604     }
605
606     /**
607      * Constructs a newly allocated <code>Integer</code> object that
608      * represents the <code>int</code> value indicated by the
609      * <code>String</code> parameter. The string is converted to an
610      * <code>int</code> value in exactly the manner used by the
611      * <code>parseInt</code> method for radix 10.
612      *
613      * @param s the <code>String</code> to be converted to an
614      * <code>Integer</code>.
615      * @exception NumberFormatException if the <code>String</code> does not
616      * contain a parsable integer.
617      * @see java.lang.Integer#parseInt(java.lang.String, int)
618      */

619     public Integer(String JavaDoc s) throws NumberFormatException JavaDoc {
620     this.value = parseInt(s, 10);
621     }
622
623     /**
624      * Returns the value of this <code>Integer</code> as a
625      * <code>byte</code>.
626      */

627     public byte byteValue() {
628     return (byte)value;
629     }
630
631     /**
632      * Returns the value of this <code>Integer</code> as a
633      * <code>short</code>.
634      */

635     public short shortValue() {
636     return (short)value;
637     }
638
639     /**
640      * Returns the value of this <code>Integer</code> as an
641      * <code>int</code>.
642      */

643     public int intValue() {
644     return value;
645     }
646
647     /**
648      * Returns the value of this <code>Integer</code> as a
649      * <code>long</code>.
650      */

651     public long longValue() {
652     return (long)value;
653     }
654
655     /**
656      * Returns the value of this <code>Integer</code> as a
657      * <code>float</code>.
658      */

659     public float floatValue() {
660     return (float)value;
661     }
662
663     /**
664      * Returns the value of this <code>Integer</code> as a
665      * <code>double</code>.
666      */

667     public double doubleValue() {
668     return (double)value;
669     }
670
671     /**
672      * Returns a <code>String</code> object representing this
673      * <code>Integer</code>'s value. The value is converted to signed
674      * decimal representation and returned as a string, exactly as if
675      * the integer value were given as an argument to the {@link
676      * java.lang.Integer#toString(int)} method.
677      *
678      * @return a string representation of the value of this object in
679      * base&nbsp;10.
680      */

681     public String JavaDoc toString() {
682     return String.valueOf(value);
683     }
684
685     /**
686      * Returns a hash code for this <code>Integer</code>.
687      *
688      * @return a hash code value for this object, equal to the
689      * primitive <code>int</code> value represented by this
690      * <code>Integer</code> object.
691      */

692     public int hashCode() {
693     return value;
694     }
695
696     /**
697      * Compares this object to the specified object. The result is
698      * <code>true</code> if and only if the argument is not
699      * <code>null</code> and is an <code>Integer</code> object that
700      * contains the same <code>int</code> value as this object.
701      *
702      * @param obj the object to compare with.
703      * @return <code>true</code> if the objects are the same;
704      * <code>false</code> otherwise.
705      */

706     public boolean equals(Object JavaDoc obj) {
707     if (obj instanceof Integer JavaDoc) {
708         return value == ((Integer JavaDoc)obj).intValue();
709     }
710     return false;
711     }
712
713     /**
714      * Determines the integer value of the system property with the
715      * specified name.
716      * <p>
717      * The first argument is treated as the name of a system property.
718      * System properties are accessible through the
719      * {@link java.lang.System#getProperty(java.lang.String)} method. The
720      * string value of this property is then interpreted as an integer
721      * value and an <code>Integer</code> object representing this value is
722      * returned. Details of possible numeric formats can be found with
723      * the definition of <code>getProperty</code>.
724      * <p>
725      * If there is no property with the specified name, if the specified name
726      * is empty or <code>null</code>, or if the property does not have
727      * the correct numeric format, then <code>null</code> is returned.
728      * <p>
729      * In other words, this method returns an <code>Integer</code>
730      * object equal to the value of:
731      *
732      * <blockquote><code>
733      * getInteger(nm, null)
734      * </code></blockquote>
735      *
736      * @param nm property name.
737      * @return the <code>Integer</code> value of the property.
738      * @see java.lang.System#getProperty(java.lang.String)
739      * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
740      */

741     public static Integer JavaDoc getInteger(String JavaDoc nm) {
742     return getInteger(nm, null);
743     }
744
745     /**
746      * Determines the integer value of the system property with the
747      * specified name.
748      * <p>
749      * The first argument is treated as the name of a system property.
750      * System properties are accessible through the {@link
751      * java.lang.System#getProperty(java.lang.String)} method. The
752      * string value of this property is then interpreted as an integer
753      * value and an <code>Integer</code> object representing this value is
754      * returned. Details of possible numeric formats can be found with
755      * the definition of <code>getProperty</code>.
756      * <p>
757      * The second argument is the default value. An <code>Integer</code> object
758      * that represents the value of the second argument is returned if there
759      * is no property of the specified name, if the property does not have
760      * the correct numeric format, or if the specified name is empty or
761      * <code>null</code>.
762      * <p>
763      * In other words, this method returns an <code>Integer</code> object
764      * equal to the value of:
765      * <blockquote><code>
766      * getInteger(nm, new Integer(val))
767      * </code></blockquote>
768      * but in practice it may be implemented in a manner such as:
769      * <blockquote><pre>
770      * Integer result = getInteger(nm, null);
771      * return (result == null) ? new Integer(val) : result;
772      * </pre></blockquote>
773      * to avoid the unnecessary allocation of an <code>Integer</code>
774      * object when the default value is not needed.
775      *
776      * @param nm property name.
777      * @param val default value.
778      * @return the <code>Integer</code> value of the property.
779      * @see java.lang.System#getProperty(java.lang.String)
780      * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
781      */

782     public static Integer JavaDoc getInteger(String JavaDoc nm, int val) {
783         Integer JavaDoc result = getInteger(nm, null);
784         return (result == null) ? new Integer JavaDoc(val) : result;
785     }
786
787     /**
788      * Returns the integer value of the system property with the
789      * specified name. The first argument is treated as the name of a
790      * system property. System properties are accessible through the
791      * {@link java.lang.System#getProperty(java.lang.String)} method.
792      * The string value of this property is then interpreted as an
793      * integer value, as per the <code>Integer.decode</code> method,
794      * and an <code>Integer</code> object representing this value is
795      * returned.
796      * <p>
797      * <ul><li>If the property value begins with the two ASCII characters
798      * <code>0x</code> or the ASCII character <code>#</code>, not
799      * followed by a minus sign, then the rest of it is parsed as a
800      * hexadecimal integer exactly as by the method
801      * {@link #valueOf(java.lang.String, int)} with radix 16.
802      * <li>If the property value begins with the ASCII character
803      * <code>0</code> followed by another character, it is parsed as an
804      * octal integer exactly as by the method
805      * {@link #valueOf(java.lang.String, int)} with radix 8.
806      * <li>Otherwise, the property value is parsed as a decimal integer
807      * exactly as by the method {@link #valueOf(java.lang.String, int)}
808      * with radix 10.
809      * </ul><p>
810      * The second argument is the default value. The default value is
811      * returned if there is no property of the specified name, if the
812      * property does not have the correct numeric format, or if the
813      * specified name is empty or <code>null</code>.
814      *
815      * @param nm property name.
816      * @param val default value.
817      * @return the <code>Integer</code> value of the property.
818      * @see java.lang.System#getProperty(java.lang.String)
819      * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
820      * @see java.lang.Integer#decode
821      */

822     public static Integer JavaDoc getInteger(String JavaDoc nm, Integer JavaDoc val) {
823     String JavaDoc v = null;
824         try {
825             v = System.getProperty(nm);
826         } catch (IllegalArgumentException JavaDoc e) {
827         } catch (NullPointerException JavaDoc e) {
828         }
829     if (v != null) {
830         try {
831         return Integer.decode(v);
832         } catch (NumberFormatException JavaDoc e) {
833         }
834     }
835     return val;
836     }
837
838     /**
839      * Decodes a <code>String</code> into an <code>Integer</code>.
840      * Accepts decimal, hexadecimal, and octal numbers given
841      * by the following grammar:
842      *
843      * <blockquote>
844      * <dl>
845      * <dt><i>DecodableString:</i>
846      * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
847      * <dd><i>Sign<sub>opt</sub></i> <code>0x</code> <i>HexDigits</i>
848      * <dd><i>Sign<sub>opt</sub></i> <code>0X</code> <i>HexDigits</i>
849      * <dd><i>Sign<sub>opt</sub></i> <code>#</code> <i>HexDigits</i>
850      * <dd><i>Sign<sub>opt</sub></i> <code>0</code> <i>OctalDigits</i>
851      * <p>
852      * <dt><i>Sign:</i>
853      * <dd><code>-</code>
854      * </dl>
855      * </blockquote>
856      *
857      * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
858      * are defined in <a HREF="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48282">&sect;3.10.1</a>
859      * of the <a HREF="http://java.sun.com/docs/books/jls/html/">Java
860      * Language Specification</a>.
861      * <p>
862      * The sequence of characters following an (optional) negative
863      * sign and/or radix specifier (&quot;<code>0x</code>&quot;,
864      * &quot;<code>0X</code>&quot;, &quot;<code>#</code>&quot;, or
865      * leading zero) is parsed as by the <code>Integer.parseInt</code>
866      * method with the indicated radix (10, 16, or 8). This sequence
867      * of characters must represent a positive value or a {@link
868      * NumberFormatException} will be thrown. The result is negated
869      * if first character of the specified <code>String</code> is the
870      * minus sign. No whitespace characters are permitted in the
871      * <code>String</code>.
872      *
873      * @param nm the <code>String</code> to decode.
874      * @return a <code>Integer</code> object holding the <code>int</code>
875      * value represented by <code>nm</code>
876      * @exception NumberFormatException if the <code>String</code> does not
877      * contain a parsable integer.
878      * @see java.lang.Integer#parseInt(java.lang.String, int)
879      * @since 1.2
880      */

881     public static Integer JavaDoc decode(String JavaDoc nm) throws NumberFormatException JavaDoc {
882         int radix = 10;
883         int index = 0;
884         boolean negative = false;
885         Integer JavaDoc result;
886
887         // Handle minus sign, if present
888
if (nm.startsWith("-")) {
889             negative = true;
890             index++;
891         }
892
893         // Handle radix specifier, if present
894
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
895         index += 2;
896             radix = 16;
897     }
898     else if (nm.startsWith("#", index)) {
899         index ++;
900             radix = 16;
901     }
902     else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
903         index ++;
904             radix = 8;
905     }
906
907         if (nm.startsWith("-", index))
908             throw new NumberFormatException JavaDoc("Negative sign in wrong position");
909
910         try {
911             result = Integer.valueOf(nm.substring(index), radix);
912             result = negative ? new Integer JavaDoc(-result.intValue()) : result;
913         } catch (NumberFormatException JavaDoc e) {
914             // If number is Integer.MIN_VALUE, we'll end up here. The next line
915
// handles this case, and causes any genuine format error to be
916
// rethrown.
917
String JavaDoc constant = negative ? new String JavaDoc("-" + nm.substring(index))
918                                        : nm.substring(index);
919             result = Integer.valueOf(constant, radix);
920         }
921         return result;
922     }
923
924     /**
925      * Compares two <code>Integer</code> objects numerically.
926      *
927      * @param anotherInteger the <code>Integer</code> to be compared.
928      * @return the value <code>0</code> if this <code>Integer</code> is
929      * equal to the argument <code>Integer</code>; a value less than
930      * <code>0</code> if this <code>Integer</code> is numerically less
931      * than the argument <code>Integer</code>; and a value greater
932      * than <code>0</code> if this <code>Integer</code> is numerically
933      * greater than the argument <code>Integer</code> (signed
934      * comparison).
935      * @since 1.2
936      */

937     public int compareTo(Integer JavaDoc anotherInteger) {
938     int thisVal = this.value;
939     int anotherVal = anotherInteger.value;
940     return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
941     }
942
943
944     // Bit twiddling
945

946     /**
947      * The number of bits used to represent an <tt>int</tt> value in two's
948      * complement binary form.
949      *
950      * @since 1.5
951      */

952     public static final int SIZE = 32;
953  
954     /**
955      * Returns an <tt>int</tt> value with at most a single one-bit, in the
956      * position of the highest-order ("leftmost") one-bit in the specified
957      * <tt>int</tt> value. Returns zero if the specified value has no
958      * one-bits in its two's complement binary representation, that is, if it
959      * is equal to zero.
960      *
961      * @return an <tt>int</tt> value with a single one-bit, in the position
962      * of the highest-order one-bit in the specified value, or zero if
963      * the specified value is itself equal to zero.
964      * @since 1.5
965      */

966     public static int highestOneBit(int i) {
967         // HD, Figure 3-1
968
i |= (i >> 1);
969         i |= (i >> 2);
970         i |= (i >> 4);
971         i |= (i >> 8);
972         i |= (i >> 16);
973         return i - (i >>> 1);
974     }
975  
976     /**
977      * Returns an <tt>int</tt> value with at most a single one-bit, in the
978      * position of the lowest-order ("rightmost") one-bit in the specified
979      * <tt>int</tt> 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 <tt>int</tt> value with a single one-bit, in the position
984      * of the lowest-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 lowestOneBit(int i) {
989         // HD, Section 2-1
990
return i & -i;
991     }
992  
993     /**
994      * Returns the number of zero bits preceding the highest-order
995      * ("leftmost") one-bit in the two's complement binary representation
996      * of the specified <tt>int</tt> value. Returns 32 if the
997      * specified value has no one-bits in its two's complement representation,
998      * in other words if it is equal to zero.
999      *
1000     * <p>Note that this method is closely related to the logarithm base 2.
1001     * For all positive <tt>int</tt> values x:
1002     * <ul>
1003     * <li>floor(log<sub>2</sub>(x)) = <tt>31 - numberOfLeadingZeros(x)</tt>
1004     * <li>ceil(log<sub>2</sub>(x)) = <tt>32 - numberOfLeadingZeros(x - 1)</tt>
1005     * </ul>
1006     *
1007     * @return the number of zero bits preceding the highest-order
1008     * ("leftmost") one-bit in the two's complement binary representation
1009     * of the specified <tt>int</tt> value, or 32 if the value
1010     * is equal to zero.
1011     * @since 1.5
1012     */

1013    public static int numberOfLeadingZeros(int i) {
1014        // HD, Figure 5-6
1015
if (i == 0)
1016            return 32;
1017        int n = 1;
1018        if (i >>> 16 == 0) { n += 16; i <<= 16; }
1019        if (i >>> 24 == 0) { n += 8; i <<= 8; }
1020        if (i >>> 28 == 0) { n += 4; i <<= 4; }
1021        if (i >>> 30 == 0) { n += 2; i <<= 2; }
1022        n -= i >>> 31;
1023        return n;
1024    }
1025 
1026    /**
1027     * Returns the number of zero bits following the lowest-order ("rightmost")
1028     * one-bit in the two's complement binary representation of the specified
1029     * <tt>int</tt> value. Returns 32 if the specified value has no
1030     * one-bits in its two's complement representation, in other words if it is
1031     * equal to zero.
1032     *
1033     * @return the number of zero bits following the lowest-order ("rightmost")
1034     * one-bit in the two's complement binary representation of the
1035     * specified <tt>int</tt> value, or 32 if the value is equal
1036     * to zero.
1037     * @since 1.5
1038     */

1039    public static int numberOfTrailingZeros(int i) {
1040        // HD, Figure 5-14
1041
int y;
1042    if (i == 0) return 32;
1043    int n = 31;
1044    y = i <<16; if (y != 0) { n = n -16; i = y; }
1045    y = i << 8; if (y != 0) { n = n - 8; i = y; }
1046    y = i << 4; if (y != 0) { n = n - 4; i = y; }
1047    y = i << 2; if (y != 0) { n = n - 2; i = y; }
1048    return n - ((i << 1) >>> 31);
1049    }
1050 
1051    /**
1052     * Returns the number of one-bits in the two's complement binary
1053     * representation of the specified <tt>int</tt> value. This function is
1054     * sometimes referred to as the <i>population count</i>.
1055     *
1056     * @return the number of one-bits in the two's complement binary
1057     * representation of the specified <tt>int</tt> value.
1058     * @since 1.5
1059     */

1060    public static int bitCount(int i) {
1061        // HD, Figure 5-2
1062
i = i - ((i >>> 1) & 0x55555555);
1063    i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
1064    i = (i + (i >>> 4)) & 0x0f0f0f0f;
1065    i = i + (i >>> 8);
1066    i = i + (i >>> 16);
1067    return i & 0x3f;
1068    }
1069 
1070    /**
1071     * Returns the value obtained by rotating the two's complement binary
1072     * representation of the specified <tt>int</tt> value left by the
1073     * specified number of bits. (Bits shifted out of the left hand, or
1074     * high-order, side reenter on the right, or low-order.)
1075     *
1076     * <p>Note that left rotation with a negative distance is equivalent to
1077     * right rotation: <tt>rotateLeft(val, -distance) == rotateRight(val,
1078     * distance)</tt>. Note also that rotation by any multiple of 32 is a
1079     * no-op, so all but the last five bits of the rotation distance can be
1080     * ignored, even if the distance is negative: <tt>rotateLeft(val,
1081     * distance) == rotateLeft(val, distance & 0x1F)</tt>.
1082     *
1083     * @return the value obtained by rotating the two's complement binary
1084     * representation of the specified <tt>int</tt> value left by the
1085     * specified number of bits.
1086     * @since 1.5
1087     */

1088    public static int rotateLeft(int i, int distance) {
1089        return (i << distance) | (i >>> -distance);
1090    }
1091
1092    /**
1093     * Returns the value obtained by rotating the two's complement binary
1094     * representation of the specified <tt>int</tt> value right by the
1095     * specified number of bits. (Bits shifted out of the right hand, or
1096     * low-order, side reenter on the left, or high-order.)
1097     *
1098     * <p>Note that right rotation with a negative distance is equivalent to
1099     * left rotation: <tt>rotateRight(val, -distance) == rotateLeft(val,
1100     * distance)</tt>. 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: <tt>rotateRight(val,
1103     * distance) == rotateRight(val, distance & 0x1F)</tt>.
1104     *
1105     * @return the value obtained by rotating the two's complement binary
1106     * representation of the specified <tt>int</tt> value right by the
1107     * specified number of bits.
1108     * @since 1.5
1109     */

1110    public static int rotateRight(int i, int distance) {
1111        return (i >>> distance) | (i << -distance);
1112    }
1113 
1114    /**
1115     * Returns the value obtained by reversing the order of the bits in the
1116     * two's complement binary representation of the specified <tt>int</tt>
1117     * value.
1118     *
1119     * @return the value obtained by reversing order of the bits in the
1120     * specified <tt>int</tt> value.
1121     * @since 1.5
1122     */

1123    public static int reverse(int i) {
1124        // HD, Figure 7-1
1125
i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
1126    i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
1127    i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
1128    i = (i << 24) | ((i & 0xff00) << 8) |
1129        ((i >>> 8) & 0xff00) | (i >>> 24);
1130    return i;
1131    }
1132 
1133    /**
1134     * Returns the signum function of the specified <tt>int</tt> value. (The
1135     * return value is -1 if the specified value is negative; 0 if the
1136     * specified value is zero; and 1 if the specified value is positive.)
1137     *
1138     * @return the signum function of the specified <tt>int</tt> value.
1139     * @since 1.5
1140     */

1141    public static int signum(int i) {
1142        // HD, Section 2-7
1143
return (i >> 31) | (-i >>> 31);
1144    }
1145 
1146    /**
1147     * Returns the value obtained by reversing the order of the bytes in the
1148     * two's complement representation of the specified <tt>int</tt> value.
1149     *
1150     * @return the value obtained by reversing the bytes in the specified
1151     * <tt>int</tt> value.
1152     * @since 1.5
1153     */

1154    public static int reverseBytes(int i) {
1155        return ((i >>> 24) ) |
1156               ((i >> 8) & 0xFF00) |
1157               ((i << 8) & 0xFF0000) |
1158               ((i << 24));
1159    }
1160
1161    /** use serialVersionUID from JDK 1.0.2 for interoperability */
1162    private static final long serialVersionUID = 1360826667806852920L;
1163}
1164
Popular Tags