JAVA源码阅读——–Short类
类定义
- Short类被final关键词修饰,不可被继承
- Short类继承Number类并实现其方法,可返回其他基本类型数据,例如longValue()返回long类型数据
- Short类实现了comparable接口,可以利用CompareTo方法与其他Short对象比较
私有属性
用于存储short对象的值
private final short value;
Short类的序列号
private static final long serialVersionUID = 7515723908773894738L;
公共属性
Short类型最大值,对应二进制 0b0111 1111 1111 1111
public static final short MAX_VALUE = 32767;
Short类型最小值,对应二进制 0b0000 0000 0000 0000
public static final short MIN_VALUE = -32768;
short的bit位数
public static final int SIZE = 16;
short的字节数
public static final int BYTES = SIZE / Byte.SIZE;
静态块
与Integer的Cache一样都是能够缓存-128~127间的数
Integer的缓存池大小可调,Short不可调
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 Short(short value) {
this.value = value;
}
public Short(String s) throws NumberFormatException {
this.value = parseShort(s, 10);
}
公共方法
返回Short对应的基类型
public static final Class<Short> TYPE = (Class<Short>) Class.getPrimitiveClass("short");
toString调用Integer的toString方法,数的大小不再MIN_VALUE~MAX_VALUE会导致数据溢出
public static String toString(short s) {
return Integer.toString((int)s, 10);
}
parseShort将字符串转换为Short类型,调用Integer类型的parseInt,数据异常抛出数据格式错误
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. Value:\"" + s + "\" Radix:" + radix);
return (short)i;
}
valueOf方法将根据short类型的数s创建Short类型,如果 -128 <= s <=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调用Integer.decode方法进行解析
public static Short decode(String nm) throws NumberFormatException {
int i = Integer.decode(nm);
if (i < MIN_VALUE || i > MAX_VALUE)
throw new NumberFormatException(
"Value " + i + " out of range from input " + nm);
return valueOf((short)i);
}
按位反转,对于2byte直接移位可以获得
public static short reverseBytes(short i) {
return (short) (((i & 0xFF00) >> 8) | (i << 8));
}