原始类型包装类解读(Short)

该类继承自Number,仅有一个final short类型的成员变量value,用来保存对应的原始类型。

静态常量

    public static final short   MIN_VALUE = -32768;
    public static final short   MAX_VALUE = 32767;
    public static final Class TYPE = (Class) short[].class.getComponentType();
    //占16bit
    public static final int SIZE = 16;
    //占2Byte
    public static final int BYTES = SIZE / Byte.SIZE;

构造函数

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

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

ShortCache

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

该类缓存了-128~127共256个Short值。

parseShort

    public static short parseShort(String s) throws NumberFormatException {
        return parseShort(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. Value:\"" + s + "\" Radix:" + radix);
        return (short)i;
    }

valueOf

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

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

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

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

学习Integer时再细说。

reverseBytes

    public static short reverseBytes(short i) {
        return (short) (((i & 0xFF00) >> 8) | (i << 8));
    }

将高8位和低8位的bit值互换。比如原值为0x0F00,则互换后为0x000F。

toUnsignedInt

    public static int toUnsignedInt(short x) {
        return ((int) x) & 0xffff;
    }

转换为无符号整型。

toUnsignedLong

    public static long toUnsignedLong(short x) {
        return ((long) x) & 0xffffL;
    }

转换为无符号长整型。

你可能感兴趣的:(原始类型包装类解读(Short))