Byte 是基本类型byte的封装类型。与Integer类似,Byte也提供了很多相同的方法,如 decode、toString、intValue、floatValue等,而且很多方法还是直接类型转换为 int型进行操作的(比如: public static String toString(byteb) {return Integer.toString((int)b, 10); } )。所以我们只是重点关注一些不同的方法或者特性。
1. 取值范围
我们知道,byte 表示的数据范围是 [-128, 127],那么Byte使用两个静态属性分别表示上界和下界:MIN_VALUE、MAX_VALUE
2. 缓存
与Integer相似,Byte也提供了缓存机制,源码如下:
private static classByteCache {privateByteCache(){}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的缓存也是 -128~127。我们已经知道,byte类型值范围就是 [-128, 127],所以Byte是对所有值都进行了缓存。
3. 构造方法和valueOf方法
Byte也提供两个构造方法,分别接受 byte 和 string 类型参数: public Byte(bytevalue) {this.value =value; } 和 public Byte(String s) throwsNumberFormatException {this.value = parseByte(s, 10); } 。使用构造方法创建对象时,会直接分配内存。而 valueOf 方法会从缓存中获取,所以一般情况下推荐使用 valueOf 获取对象实例,以节省开支。
public static Byte valueOf(byteb) {final int offset = 128;return ByteCache.cache[(int)b +offset];
}
public static Byte valueOf(String s, intradix)throwsNumberFormatException {returnvalueOf(parseByte(s, radix));
}
public static Byte valueOf(String s) throwsNumberFormatException {return valueOf(s, 10);
}
4. hashCoe 方法
Byte 类型的 hashCode 值就是它表示的值(转int)
@Overridepublic inthashCode() {returnByte.hashCode(value);
}/*** Returns a hash code for a {@codebyte} value; compatible with
* {@codeByte.hashCode()}.
*
*@paramvalue the value to hash
*@returna hash code value for a {@codebyte} value.
*@since1.8*/
public static int hashCode(bytevalue) {return (int)value;
}
5. compareTo 方法
Byte 也实现了 comparable 接口,可以比较大小。与 Integer 的 compareTo 有点不同的是,Integer 在当前值小于参数值时分别返回 -1、0、1,而Byte是返回正数、0、负数(当前值-参数值),当然,这也同样符合 comparable 的常规约定。
public intcompareTo(Byte anotherByte) {return compare(this.value, anotherByte.value);
}/*** Compares two {@codebyte} values numerically.
* The value returned is identical to what would be returned by:
*
* Byte.valueOf(x).compareTo(Byte.valueOf(y))
*
*
*@paramx the first {@codebyte} to compare
*@paramy the second {@codebyte} to compare
*@returnthe value {@code0} if {@codex == y};
* a value less than {@code0} if {@codex < y}; and
* a value greater than {@code0} if {@codex > y}
*@since1.7*/
public static int compare(byte x, bytey) {return x -y;
}
完!