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;
    }

 

完!

相關文章
相關標籤/搜索