1、定义常量,byte取值范围-128~127,位数为8位
/**
* A constant holding the minimum value a {@code byte} can
* have, -2<sup>7</sup>.
*/
public static final byte MIN_VALUE = -128;
/**
* A constant holding the maximum value a {@code byte} can
* have, 2<sup>7</sup>-1.
*/
public static final byte MAX_VALUE = 127;
/**
* The number of bits used to represent a {@code byte} value in two's
* complement binary form.
*
* @since 1.5
*/
public static final int SIZE = 8;
2、toString
返回十进制数值
public String toString() {
return Integer.toString((int)value);
}
3、hashCode
byte的int值
@Override
public int hashCode() {
return Byte.hashCode(value);
}
public static int hashCode(byte value) {
return (int)value;
}
4、valueOf
byte只有256个值,初始化对象后放入缓存中,直接读取。
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));
}
}
public static Byte valueOf(byte b) {
final int offset = 128;
return ByteCache.cache[(int)b + offset];
}
5、parseByte
解析字符串时,以Integer进行解析成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;
}
public static byte parseByte(String s) throws NumberFormatException {
return parseByte(s, 10);
}
6、字符串构造函数
以字符串十进制进行解析
public Byte(String s) throws NumberFormatException {
this.value = parseByte(s, 10);
}