1类的声明
public final class Byte extends Number implements Comparable<Byte>
- 继承了Number,可用于Number子类的相互转化
- 实现了 comparable接口,可用于比较
- 是用 final修饰的,不可以继承
2静态变量
public static final byte MIN_VALUE = -128;//1
public static final byte MAX_VALUE = 127;//2
public static final int SIZE = 8;//3
public static final int BYTES = SIZE / Byte.SIZE;//4
- 1定义最小值
- 2定义最大值
- 3定义位的大小
- 4给出byte占的位的大小为1位。
3构造函数
public Byte(byte value) {
this.value = value;
}
public Byte(String s) throws NumberFormatException {
this.value = parseByte(s, 10);
}
public static byte parseByte(String s, int radix)
throws NumberFormatException {
int i = Integer.parseInt(s, radix);//1
if (i < MIN_VALUE || i > MAX_VALUE)
throw new NumberFormatException(
"Value out of range. Value:\"" + s + "\" Radix:" + radix);
return (byte)i;//2
}
- 1处是对string类型转化为10进制整数
- 2处直接强制转换
- 其实把string转成整型,再把整型转为byte
4方法
4.1toString(byte b)
public static String toString(byte b) {
return Integer.toString((int)b, 10);
}
直接调用个是Integer的tostring方法
4.2valueOf(byte b)
public static Byte valueOf(byte b) {
final int offset = 128;//1
return ByteCache.cache[(int)b + offset];//2
}
public static Byte valueOf(String s, int radix)
throws NumberFormatException {
return valueOf(parseByte(s, radix));
}
2处的意思是直接从缓存里面获取值,由于缓存是从 -128-127 的因此需要加上128。
4.3parseByte(String s, int radix)
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;
}
直接调用的是Integer的方法......
4.4decode(String nm)
将字符串转为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);
}
还是用的整数类型的代码
4.5hashCode()
public int hashCode() {
return Byte.hashCode(value);
}
public static int hashCode(byte value) {
return (int)value;
}
hash直接返回的就是本体的value
5内部类
5.1ByteCache
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));
}
}
这是一个内部类,用来存储所有的字符,当初始值有超过范围,便会循环遍历这个数组来获取值