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

 

完!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM