jdk源码之重新认识Byte

159 阅读3分钟

面试题

1、Java面试题 :byte b = (byte)128; 定义变量语句是否正确?byte b = 128呢?

2、代码段

byte b1=1,b2=2,b3,b6;
final byte b4=4,b5=6;
b6 = b4+b5;
b3=(b1+b2);
System.out.println(b3+b6);

请问这段代码运行时什么结果?

3、请说下下面代码的打印值

public static void main(String[] args){
    Byte a = 127;
    Byte aByte = Byte.valueOf("127");
    System.out.println(a==aByte);
    Byte bByte = new Byte("127");
    System.out.println(a==bByte);
}

Byte的继承关系

public final class Byte extends Number implements Comparable<Byte>, Constable 

Byte是继承了Number抽象类,Number抽象类中主要定义了类型转换的方法,如:intValue(); longValue()... Byte还实现了Constable,说明值是稳定的,可以放到常量池中。实现Comparable接口说明可以实现

public int compareTo(T o);

方法来排序。

Byte中的成员变量方法总览

image.png

构造方法

public Byte(byte value)

/**
 * 构造表示指定byte值的新分配Byte的对象。
 * 荒废的
 * 很少适合使用此构造函数。静态工厂 valueOf(byte) 通常是更好的选择,
 * 因为它可能会产生明显更好的空间和时间性能。
 * 参数:
 * value – 要由 表示 Byte的值。
 */
@Deprecated(since="9", forRemoval = true)
public Byte(byte value) {
    this.value = value;
}

使用此构造方法会新分配对象内存并返回对象引用,java9弃用,原因是valueOf(byte) 方法更推荐,可以节省空间和时间。

public Byte(String s)

/**
 * 构造一个新分配 Byte 的对象,该对象表示 byte 参数指示 String 的值。字符串以 byte 完全按照基数 10 的方法使用 parseByte 的方式转换为值。
 * 荒废的
 * 很少适合使用此构造函数。用于将字符串转换为基元,或用于   parseByte(String)valueOf(String)将字符串byteByte转换为对象。
 * 参数:
 * sString– 要转换为Byte
 * 抛出:
 * NumberFormatException – 如果不包含 String 可解析的 byte.
 */
@Deprecated(since="9", forRemoval = true)
public Byte(String s) throws NumberFormatException {
    this.value = parseByte(s, 10);
}

此构造方法也是会分配对象内存并返回引用,浪费空间时间,建议使用parseByte(String)方法,或者 valueOf(String)方法。两个方法返回的值得地址都是相同的。

类型转换方法

public byte byteValue() {
    return value;
}
public short shortValue() {
    return (short)value;
}
public double doubleValue() {
    return (double)value;
}
public float floatValue() {
    return (float)value;
}
public int intValue() {
    return (int)value;
}
public long longValue() {
    return (long)value;
}

不多解释,除了本身外,都是强转换。

比较方法

compare

/**
* 以数字方式比较两个 Byte 对象。
* 相等返回0,本值大于入参值返回值大于0,否则小于0。
* @since 1.2
 */
public int compareTo(Byte anotherByte) {
    return compare(this.value, anotherByte.value);
}

/**
 * 
 *@since 1.7
 */
public static int compare(byte x, byte y) {
    return x - y;
}

/**
 * 比较两个 byte 值,以数字方式将这值视为无符号。
 * @since 9
 */
public static int compareUnsigned(byte x, byte y) {
    return Byte.toUnsignedInt(x) - Byte.toUnsignedInt(y);
}

equals

public boolean equals(Object obj) {
    if (obj instanceof Byte) {
        return value == ((Byte)obj).byteValue();
    }
    return false;
}

hashCode

/**
 * 返回对象hashCode值
 */
@Override
public int hashCode() {
    return Byte.hashCode(value);
}

/**
 * @since 1.8
 */
public static int hashCode(byte value) {
    // 注意此处直接返回int
    return (int)value;
}

parseByte

调用Integer.parseInt方法返回int 然后转为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;
}

默认10进制parseByte

public static byte parseByte(String s) throws NumberFormatException {
    return parseByte(s, 10);
}

valueOf

valueOf是直接从缓存中取出Byte

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

若是入参是String则需要parseByte

public static Byte valueOf(String s) throws NumberFormatException {
    return valueOf(s, 10);
}
public static Byte valueOf(String s, int radix)
    throws NumberFormatException {
    return valueOf(parseByte(s, radix));
}
private static class ByteCache {
    private ByteCache() {}

    static final Byte[] cache;
    static Byte[] archivedCache;

    static {
        final int size = -(-128) + 127 + 1;

        // Load and use the archived cache if it exists
        CDS.initializeFromArchive(ByteCache.class);
        if (archivedCache == null || archivedCache.length != size) {
            Byte[] c = new Byte[size];
            byte value = (byte)-128;
            for(int i = 0; i < size; i++) {
                c[i] = new Byte(value++);
            }
            archivedCache = c;
        }
        cache = archivedCache;
    }
}

decode

调用Integer.decode方法得到int,然后取缓存中的对象

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

转为无符号数

/**
 * @since 1.8
 */
public static int toUnsignedInt(byte x) {
    return ((int) x) & 0xff;
}

/**
 * @since 1.8
 */
public static long toUnsignedLong(byte x) {
    return ((long) x) & 0xffL;
}