Byte
定义了取值范围
public static final byte MIN_VALUE = -128; public static final byte MAX_VALUE = 127;
调用 Integer 的方法进行 Byte 转 String
public static String toString(byte b) {
return Integer.toString((int)b, 10);
}
定义了内部静态缓存类,提高性能
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)); } }
byte 转 Byte 对象
public static Byte valueOf(byte b) {
final int offset = 128;
return ByteCache.cache[(int)b + offset];
}
取缓存里面的对象。
*字符串转 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;
}
public static byte parseByte(String s) throws NumberFormatException {
return parseByte(s, 10);
}
底层实现还是使用 Integer 对象进行解析。
字符串转 Byte 对象
public static Byte valueOf(String s, int radix) throws NumberFormatException { return valueOf(parseByte(s, radix)); } public static Byte valueOf(String s) throws NumberFormatException { return valueOf(s, 10); }
先通过 Integer,将字符串转 为byte 值,再从缓存中取出对应值的 Byte 对象。
解析带符号的进制数
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 提供的方法
提供2个构造器创建Byte对象
public Byte(byte value) {
this.value = value;
}
public Byte(String s) throws NumberFormatException {
this.value = parseByte(s, 10);
}
数值转换
public byte byteValue() {
return value;
}
public short shortValue() {
return (short)value;
}
public int intValue() {
return (int)value;
}
public long longValue() {
return (long)value;
}
public float floatValue() {
return (float)value;
}
public double doubleValue() {
return (double)value;
}
public String toString() {
return Integer.toString((int)value);
}
实现了 Number 类,需要实现这些方法。toString 除外。
hashCode、equals、compare函数
@Override public int hashCode() { return Byte.hashCode(value); } public static int hashCode(byte value) { return (int)value; } public boolean equals(Object obj) { if (obj instanceof Byte) { return value == ((Byte)obj).byteValue(); } return false; } public int compareTo(Byte anotherByte) { return compare(this.value, anotherByte.value); } public static int compare(byte x, byte y) { return x - y; }
转无符号 int 和 long 数方法
public static int toUnsignedInt(byte x) {
return ((int) x) & 0xff;
}
public static long toUnsignedLong(byte x) {
return ((long) x) & 0xffL;
}
不知用处,暂时忽略。