java封装数据类型——Byte
Byte 是基本类型byte的封装类型。与Integer类似,Byte也提供了很多相同的方法,如 decode、toString、intValue、floatValue等,而且很多方法还是直接类型转换为 int型进行操作的(比如: public static String toString(byte b) { return Integer.toString((int)b, ); } )。所以我们只是重点关注一些不同的方法或者特性。
1. 取值范围
我们知道,byte 表示的数据范围是 [-128, 127],那么Byte使用两个静态属性分别表示上界和下界:MIN_VALUE、MAX_VALUE
2. 缓存
与Integer相似,Byte也提供了缓存机制,源码如下:
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的缓存也是 -128~127。我们已经知道,byte类型值范围就是 [-128, 127],所以Byte是对所有值都进行了缓存。
3. 构造方法和valueOf方法
Byte也提供两个构造方法,分别接受 byte 和 string 类型参数: public Byte(byte value) { this.value = value; } 和 public Byte(String s) throws NumberFormatException { this.value = parseByte(s, 10); } 。使用构造方法创建对象时,会直接分配内存。而 valueOf 方法会从缓存中获取,所以一般情况下推荐使用 valueOf 获取对象实例,以节省开支。
public static Byte valueOf(byte b) {
final int offset = 128;
return ByteCache.cache[(int)b + offset];
}
public static Byte valueOf(String s, int radix)
throws NumberFormatException {
return valueOf(parseByte(s, radix));
}
public static Byte valueOf(String s) throws NumberFormatException {
return valueOf(s, 10);
}
4. hashCoe 方法
Byte 类型的 hashCode 值就是它表示的值(转int)
@Override
public int hashCode() {
return Byte.hashCode(value);
} /**
* Returns a hash code for a {@code byte} value; compatible with
* {@code Byte.hashCode()}.
*
* @param value the value to hash
* @return a hash code value for a {@code byte} value.
* @since 1.8
*/
public static int hashCode(byte value) {
return (int)value;
}
5. compareTo 方法
Byte 也实现了 comparable 接口,可以比较大小。与 Integer 的 compareTo 有点不同的是,Integer 在当前值小于参数值时分别返回 -1、0、1,而Byte是返回正数、0、负数(当前值-参数值),当然,这也同样符合 comparable 的常规约定。
public int compareTo(Byte anotherByte) {
return compare(this.value, anotherByte.value);
} /**
* Compares two {@code byte} values numerically.
* The value returned is identical to what would be returned by:
* <pre>
* Byte.valueOf(x).compareTo(Byte.valueOf(y))
* </pre>
*
* @param x the first {@code byte} to compare
* @param y the second {@code byte} to compare
* @return the value {@code 0} if {@code x == y};
* a value less than {@code 0} if {@code x < y}; and
* a value greater than {@code 0} if {@code x > y}
* @since 1.7
*/
public static int compare(byte x, byte y) {
return x - y;
}
完!
最新文章
- 导出resource文件的的资源
- HTML5_用语义化标记重新定义博客
- CORS 跨域
- Eclipse 打包过滤 Log.e
- POJ-1324-Holedox Moving(BFS)
- 生产都消费者模式的一个demo,消费者设置缓存
- c#自带压缩类实现数据库表导出到CSV压缩文件
- Linux进程通信学习总结
- 心智与认知(1): 反馈循环(Feedback loop)
- java基础:子类-父类构造器关系
- Linux监控命令整理(top,free,vmstat,iostat,mpstat,sar,netstat)
- 开始学习tensorflow
- Linux 安装Python虚拟环境,virtualenvwrapper
- mysql 批量修改字段方法
- 记一次Spring的aop代理Mybatis的DAO所遇到的问题
- 打造 Vue.js 可复用组件
- yum &;&; 编译 安装mysql 5.7 多实例
- 2018年星际争霸AI挑战赛–三星与FB获冠亚军,中科院自动化所夺得季军
- node使用MySQL数据库
- jap -文档 https://www.tutorialspoint.com/jpa/jpa_jpql.htm