JAVA源码阅读——–Short类

JAVA源码阅读——–Short类

类定义

  1. Short类被final关键词修饰,不可被继承
  2. Short类继承Number类并实现其方法,可返回其他基本类型数据,例如longValue()返回long类型数据
  3. 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));
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值