首页 / JAVA / java封装数据类型——Byte
java封装数据类型——Byte
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java封装数据类型——Byte,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2410字,纯文字阅读大概需要4分钟。
内容图文
Byte 是基本类型byte的封装类型。与Integer类似,Byte也提供了很多相同的方法,如 decode、toString、intValue、floatValue等,而且很多方法还是直接类型转换为 int型进行操作的(比如: publicstatic String toString(byte b) { return Integer.toString((int)b, 10); } )。所以我们只是重点关注一些不同的方法或者特性。
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) { finalint 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 */publicstaticint compare(byte x, byte y) { return x - y; }
完!
原文:https://www.cnblogs.com/coding-one/p/11725145.html
内容总结
以上是互联网集市为您收集整理的java封装数据类型——Byte全部内容,希望文章能够帮你解决java封装数据类型——Byte所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。