美文网首页
原始类型包装类解读(Byte)

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

作者: sollian | 来源:发表于2018-06-20 16:42 被阅读13次

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

静态常量

//byte类型的最小值
public static final byte MIN_VALUE = -128;
//byte类型的最大值
public static final byte MAX_VALUE = 127;
//原始类型
public static final Class<Byte> TYPE = (Class<Byte>) byte[].class.getComponentType();
//1字节包含的bit数
public static final int SIZE = 8;
//1字节包含的字节数(自己当然只包含一个自己了😝)
public static final int BYTES = SIZE / Byte.SIZE;

构造函数

    public Byte(byte value) {
        this.value = value;
    }

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

ByteCache

    private static class ByteCache {
        private ByteCache(){}

        static final Byte cache[] = new Byte[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Byte((byte)(i - 128));
        }
    }

该类有一个大小为256的数组,缓存了Byte所有的值。

valueOf

    public static Byte valueOf(byte b) {
        final int offset = 128;
        return ByteCache.cache[(int)b + offset];
    }

从ByteCache中取出对应的包装类,并返回。

parseByte

    public static byte parseByte(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 (byte)i;
    }

先将字符串s转换为整型值,再强转为Byte值。radix为进制,稍后学习Integer时再深入探讨。

其他方法
public static byte parseByte(String s)
public static Byte valueOf(String s, int radix)
public static Byte valueOf(String s)
均是对以上两个方法的变形,不再赘述。

decode

    public static Byte 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((byte)i);
    }

学习Integer类时再细说。

toUnsignedInt

    public static int toUnsignedInt(byte x) {
        return ((int) x) & 0xff;
    }

转换为无符号整型。

toUnsignedLong

    public static long toUnsignedLong(byte x) {
        return ((long) x) & 0xffL;
    }

转换为无符号长整型。

相关文章

网友评论

      本文标题:原始类型包装类解读(Byte)

      本文链接:https://www.haomeiwen.com/subject/rudreftx.html