Java 源码 - Short


介绍

The Short class wraps a value of primitive type short in an object.

示例

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

源码

public final class Short extends Number implements Comparable {

  /**
   * -215.
   */
  public static final short   MIN_VALUE = -32768;

  /**
   * 215-1.
   */
  public static final short   MAX_VALUE = 32767;

  public static String toString(short s) {
    return Integer.toString((int)s, 10);
  }

  public static short parseShort(String s, int radix)
    throws NumberFormatException {
    int i = Integer.parseInt(s, radix);
    if (i < MIN_VALUE || i > MAX_VALUE)
      throw new NumberFormatException("Value out of range.");
    return (short)i;
  }

  public static Short valueOf(String s, int radix)
    throws NumberFormatException {
    return valueOf(parseShort(s, radix));
  }


  private static class ShortCache {
    private ShortCache(){}

    static final Short cache[] = new Short[-(-128) + 127 + 1];

    static {
      for(int i = 0; i < cache.length; i++)
        cache[i] = new Short((short)(i - 128));
    }
  }

  public static Short valueOf(short s) {
    final int offset = 128;
    int sAsInt = s;
    if (sAsInt >= -128 && sAsInt <= 127) {
      return ShortCache.cache[sAsInt + offset];
    }
    return new Short(s);
  }

  private final short value;

  public Short(short value) {
    this.value = value;
  }

  public Short(String s) throws NumberFormatException {
    this.value = parseShort(s, 10);
  }

  public String toString() {
    return Integer.toString((int)value);
  }

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

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

  public static int compare(short x, short y) {
    return x - y;
  }
}