Byte
public final class Byte extends Number implements Comparable<Byte>
public static final byte MIN_VALUE = -128;
public static final byte MAX_VALUE = 127;
继承Number表示为一个数字,最小值-128最大值127
public static final Class<Byte> TYPE = (Class<Byte>) Class.getPrimitiveClass("byte");
TYPE表示为byte基础类型的包装类
public static String toString(byte b) {
return Integer.toString((int)b, 10);
}
toString方法调用的是Integer的toString方法
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));
}
}
私有静态类ByteCache保存了Byte值的缓存从-128到127的int值,容量为128+127+1,实际下标为0~256
public static Byte valueOf(byte b) {
final int offset = 128;
return ByteCache.cache[(int)b + offset];
}
从cache缓存中取值,offset需要添加上128才是正确的位置
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;
}
字符串转byte,使用Integer.parseInt后续分析到Integer再解析,判断是否中最大值与最小值范围内,强转为byte基础类型,radix表示进制
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);
}
将不同进制的字符串转换为Byte类型,使用Integer的decode方法
private final byte value;
保存当前对象值
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);
}
构造器及获取不同类型value值,根据类型直接强制转换
public int hashCode() {
return Byte.hashCode(value);
}
public static int hashCode(byte value) {
return (int)value;
}
hashCode方法不需要计算,直接使用value值
public boolean equals(Object obj) {
if (obj instanceof Byte) {
return value == ((Byte)obj).byteValue();
}
return false;
}
使用byteValue()方法最对比
public int compareTo(Byte anotherByte) {
return compare(this.value, anotherByte.value);
}
public static int compare(byte x, byte y) {
return x - y;
}
对比方法直接两个数相减
public static int toUnsignedInt(byte x) {
return ((int) x) & 0xff;
}
public static long toUnsignedLong(byte x) {
return ((long) x) & 0xffL;
}
转为无符号int和long
public static final int SIZE = 8;
public static final int BYTES = SIZE / Byte.SIZE;
SIZE表示字节位数(8位),BYTES表示一个字节