Byte类是基本类型byte的包装类。
类定义:
public final class Byte extends Number implements Comparable<Byte>
属性:
私有属性:
private final byte value;(value属性就是Byte对象中真正保存int值的)
公共属性:
public static final byte MIN_VALUE = -128;
public static final byte MAX_VALUE = 127;
public static final Class<Byte> TYPE = Class.getPrimitiveClass("byte");
public static final int SIZE = 8;
方法:
Integer提供了两个构造方法:
//构造一个新分配的 Byte 对象,它表示指定的 byte 值。
public Byte(byte arg0) {
this.value = arg0;
}
//构造一个新分配的 Byte 对象,它表示 String 参数所指示的 byte 值。
public Byte(String arg0) throws NumberFormatException {
this.value = parseByte(arg0, 10);
}
Byte valueOf(byte arg)方法(effective java第一条准则):
//valueOf方法源码
public static Byte valueOf(byte arg) {
return Byte.ByteCache.cache[arg + 128];
}
Byte类和Integer一样,调用valueOf方法时,会从缓存中取,不过不同的是Byte类调用valueOf取得都是缓存ByteCache中的值。
private static class ByteCache {
static final Byte[] cache = new Byte[256];
static {
for (int arg = 0; arg < cache.length; ++arg) {
cache[arg] = new Byte((byte) (arg - 128));
}
}
}
作为Byte类的静态内部类,和Byte类一起加载,加载过程中会创建一个长度为256的数组,同时在静态内部块中初始化。
String转成Byte(byte)的方法:
Byte decode(String arg)
Byte valueOf(String arg, int arg0)
byte parseByte(String arg)
byte parseByte(String arg, int arg0)
上述方法都是直接或间接的先将String转化为int类型,例如parseByte(String arg, int arg0)方法首先将String转化为int,然后判断该值是否在[-128,127]之间。
public static byte parseByte(String arg, int arg0)
throws NumberFormatException {
int arg1 = Integer.parseInt(arg, arg0);
if (arg1 >= -128 && arg1 <= 127) {
return (byte) arg1;
} else {
throw new NumberFormatException("Value out of range. Value:\""
+ arg + "\" Radix:" + arg0);
}
}
int转成String的方法:
String toString(byte arg)
Byte的toString(byte arg)方法调用的是Integer的toString(byte arg,10)方法。
compareTo方法:
Byte类实现了Comparable
public int compareTo(Byte arg0) {
return compare(this.value, arg0.value);
}
public static int compare(byte arg, byte arg0) {
return arg - arg0;
}
代码实现比较简单,就是拿出其中的byte类型的value进行比较。