JDK之Number类探密(2)

来源:互联网 发布:qq群淘宝领优惠券骗局 编辑:程序博客网 时间:2024/05/16 08:44

上一篇看了Byte,它是用8位2进制补码存储的,这里归纳一下各Number的位数和取值范围:

Byte 8位 -128 ~ 127 Short 16位 -32768 ~ 32767 Integer 32位 -2^31 ~ 2^31-1 Long 64位 -2^63 ~ 2^63-1 Float 32位 ±2^127   ±2^-149 Double 64位 ±2^1023   ±2^-1074

然后我们看Short类源码,和Byte差不多。不同的是,Short里面的内部类ShortCache只存了256个数,因为把全部65536个数都存起来效率反而不高了。

private static class ShortCache {    private ShortCache() {    }    static final Short cache[] = new Short[-(-128) + 127 + 1];    //和Byte一样,缓存只存了256个?不是总共有65536个吗?    static {        for (int i = 0; i < cache.length; i++)            cache[i] = new Short((short) (i - 128));        //还是[-128, 127]?    }}
所以调用valueOf方法时,先判断是否在[-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);    //原来如此,不在缓存里只好重新构造一个Short实例了}
另外JDK1.5新增了一个方法reverseBytes
/*** 返回通过反转指定 short 值的二进制补码表示形式中字节的顺序而获得的值。* 应该是前8位和后8位字节交换吧* @since 1.5*/public static short reverseBytes(short i) {    return (short) (((i & 0xFF00) >> 8) | (i << 8));}