Byte
定义
public final class Byte extends Number implements Comparable<Byte> {}
Byte被final修饰,继承Number类,实现了Comparable接口,上篇文章介绍了这个接口,主要作用是对类对象排序。
构造方法
属性
//初始化最小值
public static final byte MIN_VALUE = -128;
//初始化最大值
public static final byte MAX_VALUE = 127;
//表示这个类是基本类型
@SuppressWarnings("unchecked")
public static final Class<Byte> TYPE = (Class<Byte>) Class.getPrimitiveClass("byte");
//存储内容,被final修饰,不能被改变
private final byte value;
//最大长度
public static final int SIZE = 8;
//1.8新特性
用于表示两个字节值的字节数补码二进制形式。
public static final int BYTES = SIZE / Byte.SIZE;
//序列化
private static final long serialVersionUID = -7183698231559129828L;
方法
//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值
public static Byte valueOf(byte b) {
final int offset = 128;
return ByteCache.cache[(int)b + offset];
}
//将String对象的指定索引字符转成Byte,如果超出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;
}
//判断String中是否包含Byte字节
public static byte parseByte(String s) throws NumberFormatException {
return parseByte(s, 10);
}
//判断String中索引位置是否包含Byte字节
public static Byte valueOf(String s, int radix)
throws NumberFormatException {
return valueOf(parseByte(s, radix));
}
//判断String中是否包含Byte字节
public static Byte valueOf(String s) throws NumberFormatException {
return valueOf(s, 10);
}
//返回字节码
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值
public byte byteValue() {
return value;
}
//排序
public short shortValue() {
return (short)value;
}
//返回byte的int值
public int intValue() {
return (int)value;
}
//返回byte 的long值
public long longValue() {
return (long)value;
}
//返回byte的float 值
public float floatValue() {
return (float)value;
}
//返回byte的double 值
public double doubleValue() {
return (double)value;
}
//byte先转成数字,再转成string
public String toString() {
return Integer.toString((int)value);
}
//重写equals方法
public boolean equals(Object obj) {
if (obj instanceof Byte) {
return value == ((Byte)obj).byteValue();
}
return false;
}
//获取哈希值
public static int hashCode(byte value) {
return (int)value;
}
public int hashCode() {
return Byte.hashCode(value);
}