java封装数据类型——Byte

  Byte 是基本类型byte的封装类型。与Integer类似,Byte也提供了很多相同的方法,如 decode、toString、intValue、floatValue等,而且很多方法还是直接类型转换为 int型进行操作的(比如: public static 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) {
        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;
    }

完!

猜你喜欢

转载自www.cnblogs.com/coding-one/p/11725145.html
今日推荐