Byte的源码探索

Byte

非可变类  final class
实现对比接口 	Comparable
继承于数字类  Number

成员变量

	byte  MIN_VALUE  最小值
	byte   MAX_VALUE 最大值
	Class<Byte>    TYPE   类类型
	byte value  初始值
	int SIZE  bit位数
	int BYTES  字节数

静态内部类

static class ByteCache 缓存类

Byte cache[]  -128~128的范围

静态代码块

static {
    
    
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Byte((byte)(i - 128));  循环初始化 -128 ~ 128
        }

构造方法

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

其实内部就是调用Ingeter的方法

成员方法

String toString(byte b) 获取数值的字符串形式

public static String toString(byte b) {
    
    
        return Integer.toString((int)b, 10);
    }

内部调用Ingeter的toString方法

static Byte valueOf(byte b) 返回包装类对象

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

直接从缓存数组返回

byte parseByte(String s, int radix) 字符串数值转换程Byte数值

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;
    }
radix为可与String转换的最小基数
内部调用Integer的 parseInt方法 
判断越界

int hashCode(byte value) 获取hash码

public static int hashCode(byte value) {
    
    
        return (int)value;   数值本身就是hash码
    }

int toUnsignedInt(byte x) 转换成Int类型

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

& 0xff 是为保证低八位不变,其他位数变成0。

如果有讲解错误,请留言联系作者及时删除,避免引导错误。

猜你喜欢

转载自blog.csdn.net/weixin_43946878/article/details/107935770