java封装数据类型——Byte

  Byte 是基本类型byte的封装类型。与Integer相似,Byte也提供了不少相同的方法,如 decode、toString、intValue、floatValue等,并且不少方法仍是直接类型转换为 int型进行操做的(好比: public static String toString(byte b) { return Integer.toString((int)b, 10); } )。因此咱们只是重点关注一些不一样的方法或者特性。缓存

1. 取值范围less

  咱们知道,byte 表示的数据范围是 [-128, 127],那么Byte使用两个静态属性分别表示上界和下界:MIN_VALUE、MAX_VALUEide

    

2. 缓存this

  与Integer类似,Byte也提供了缓存机制,源码以下:spa

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是对全部值都进行了缓存。code

3. 构造方法和valueOf方法orm

  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 方法blog

  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 在当前值小于参数值时分别返回 -一、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;
    }

 

完!

相关文章
相关标签/搜索