JDK1.8源码解读之 Short

461 阅读2分钟

概述

Short类在对象中包装了一个原始类型short的值。类型为Short的对象包含一个类型为short的字段。此外,此类还提供了几种将short转换为String以及将String转换为short的方法,以及处理常量时有用的其他常量和方法。

继承关系

public final class Short extends Number implements Comparable 继承自 Number 实现了 Comparable 接口

成员属性

  • public static final short MIN_VALUE = -32768; short表示的最小值
  • public static final short MAX_VALUE = 32767; short表示的最大值
  • public static final Class TYPE = (Class) Class.getPrimitiveClass("short"); 返回Short类型对应的基本类型的名称,即“short”
  • private final short value; 存储Short的值
  • public static final int SIZE = 16; short需要的位数。
  • public static final int BYTES = SIZE / Byte.SIZE; short占用的字节数。

构造器

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

关键方法

+ parseShort()

按照指定进制转化为short

public static short parseShort(String s, int radix)

重载方法,按照10进制

public static short parseShort(String s) throws NumberFormatException { ... }
+ valueOf()

按照指定的进制,转化为Short

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

重载方法,按照默认的进制,10进制

public static Short valueOf(String s) throws NumberFormatException {
    return valueOf(s, 10);
}
+ valueOf()

转化为Short,如果在[-128, 127],返回提前创建的对象。

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

String解码为Short

public static Short decode(String nm) throws NumberFormatException { ... }

+ byteValue()

返回对应的byte值。

public byte byteValue() {
        return (byte)value;
    }

相应的,还有intValue(), longValue(), doubleValue(), shortValue(), floatValue(),

+ equals()

和另一个对象比较。如果类型是Short,且value相等,返回true,否则返回false。

public boolean equals(Object obj) { ... }
+ compareTo()

和另一个Short比较,返回差值。

public int compareTo(Short anotherShort) {
    return compare(this.value, anotherShort.value);
}
+ compare()

返回差值。

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

内部类

存储了在[-128, 127]之间的值。如果需要该范围内的对象,直接使用已经创建的对象。

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));
    }
}

要点记录

  • 内部类的使用,预创建了一定范围内的值,已减少该范围内对象的创建,节省系统开销。

希望和大家多多交流


我16年毕业以后,做的是前端,目前打算深入学习java开发。内容有任何问题,欢迎各位小伙伴们指正,也希望小伙伴们给我点赞和关注,给我留言,一起交流讨论,共同进步。