包装类:Integer、Long、Short、Boolean、Byte、Character、Double、Float、Number
Byte:
方法 |
---|
类 |
构造函数 |
内部类 |
valueOf |
parseByte |
decode |
toString |
hashCode |
equals |
compareTo |
public final class Byte extends Number implements Comparable<Byte>
构造函数
private final byte value;
public Byte(byte value) {
this.value = value;
}
public Byte(String s) throws NumberFormatException {
this.value = parseByte(s, 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的内部类ByteCache
做什么用的?
- 从字面意思理解,他是一个缓存
- 它内部有一个Byte类型的常量数组,这个缓存的大小就是256,表示[-128,127]
- 它的内部是一个静态代码块,它在程序的运行当中只会被执行一次
- 当我们
Byte n1=127;
这个Byte就是来自ByteCahche里面的数
- 举个栗子
public class Main{
public static void main(String[] args) {
Byte n1 = 127;
Byte n2 = 127;
System.out.println(n1 == n2);
}
结果:true
**原因:所有的Byte类型的数字都是来自ByteCache
- valueOf
public static Byte valueOf(byte b) {
final int offset = 128;
return ByteCache.cache[(int)b + offset];
}
- parseByte
parseByte最终调用的是Integer.parseInt(s, 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;
}
- decode(String nm)
decode(String nm)最终调用的是Integer.decode(String nm)方法
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);
}
- toString(String nm)
toString()最终调用的是Integer.toString()方法
public String toString() {
return Integer.toString((int)value);
}
- hashCode
public static int hashCode(byte value) {
return (int)value;
}
- equals
public boolean equals(Object obj) {
if (obj instanceof Byte) {
return value == ((Byte)obj).byteValue();
}
return false;
}
- compareTo
public int compareTo(Byte anotherByte) {
return compare(this.value, anotherByte.value);
}
public static int compare(byte x, byte y) {
return x - y;
}
- 常量
private static final long serialVersionUID = -7183698231559129828L;
public static final int SIZE = 8;
public static final int BYTES = SIZE / Byte.SIZE;
public static final byte MIN_VALUE = -128;
public static final byte MAX_VALUE = 127;
public static final Class<Byte> TYPE = (Class<Byte>) Class.getPrimitiveClass("byte");
private final byte value;