Java 源码 - Integer


介绍

The Integer class wraps a value of the primitive type int in an object.

示例

public class Test {
  public static void main(String[] args) {
    Integer a = Integer.valueOf("12");
    System.out.println(Integer.toString(12));
  }
}

源码

public final class Integer extends Number implements Comparable {
  /**
   * -231.
   */
  @Native public static final int   MIN_VALUE = 0x80000000;

  /**
   * 231-1.
   */
  @Native public static final int   MAX_VALUE = 0x7fffffff;

  public static String toString(int i, int radix) {
    if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
      radix = 10;

    if (radix == 10) {
      return toString(i);
    }

    char buf[] = new char[33];
    boolean negative = (i < 0);
    int charPos = 32;

    if (!negative) {
      i = -i;
    }

    while (i <= -radix) {
      buf[charPos--] = digits[-(i % radix)];
      i = i / radix;
    }
    buf[charPos] = digits[-i];

    if (negative) {
      buf[--charPos] = '-';
    }

    return new String(buf, charPos, (33 - charPos));
  }

  private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];
    static {
      int h = 127;
      String integerCacheHighPropValue =
        sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
      if (integerCacheHighPropValue != null) {
        try {
          int i = parseInt(integerCacheHighPropValue);
          i = Math.max(i, 127);
          h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
        } catch( NumberFormatException nfe) {
         
        }
      }
      high = h;
      cache = new Integer[(high - low) + 1];
      int j = low;
      for(int k = 0; k < cache.length; k++)
        cache[k] = new Integer(j++);
      assert IntegerCache.high >= 127;
    }
    private IntegerCache() {}
  }

  public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
      return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
  }

  private final int value;

  public Integer(int value) {
    this.value = value;
  }

  public static int hashCode(int value) {
    return value;
  }

  public boolean equals(Object obj) {
    if (obj instanceof Integer) {
      return value == ((Integer)obj).intValue();
    }
    return false;
  }

  public static int compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
  }
}