java封裝數據類型——Integer


  今天來學習整型 int 的封裝數據類型,Integer。

1. 定義

  首先來看看定義。可以看到,Integer 繼承 Number 抽象類,實現了 Comparable 接口。Number 類是常用數字類型類的公共父類,它規定了其子類(通常就是數字類)必須提供將其值轉換成 int、long、float、double、byte、short 類型數據的能力。實現 Comparable 接口自然是為了比較大小。另外,Integer 類型也是最終類,不可被繼承(事實上,常用數據類型的封裝類都是 final 類)。

 

2. 屬性

  2.1. 表示 int 數據類型上下界值的字段:MIN_VALUE = -231 ,MAX_VALUE = 231-1 ;

  2.2. Integer 類型類對象的引用:TYPE;

    

 

3. 構造方法

  Integer 提供兩個構造方法,分別接收一個 int 數據類型和一個 string 類型(不是整數會報錯)。

    public Integer(int value) {
            this.value = value;
    }

    public Integer(String s) throws NumberFormatException {
        this.value = parseInt(s, 10);
    }

 

4. 普通方法

static int bitCount(int i)
返回指定的int值的二進制補碼二進制表示中的 int數。
byte byteValue()
返回此值 Integer為 byte的基本收縮轉換后。
static int compare(int x, int y)
比較兩個 int數字值。
int compareTo(Integer anotherInteger)
數字比較兩個 Integer對象。
static int compareUnsigned(int x, int y)
比較兩個 int值,以數值方式將值視為無符號。
static Integer decode(String nm)
將 String解碼成 Integer 。
static int divideUnsigned(int dividend, int divisor)
返回將第一個參數除以秒的無符號商,其中每個參數和結果被解釋為無符號值。
double doubleValue()
返回此值 Integer為 double一個寬元轉換后。
boolean equals(Object obj)
將此對象與指定的對象進行比較。
float floatValue()
返回此值 Integer為 float一個寬元轉換后。
static Integer getInteger(String nm)
確定具有指定名稱的系統屬性的整數值。
static Integer getInteger(String nm, int val)
確定具有指定名稱的系統屬性的整數值。
static Integer getInteger(String nm, Integer val)
返回具有指定名稱的系統屬性的整數值。
int hashCode()
返回這個 Integer的哈希碼。
static int hashCode(int value)
返回值為int的哈希碼; 兼容Integer.hashCode() 。
static int highestOneBit(int i)
返回一個 int值與至多一個單個1位,在最高階(“最左側”)的位置在指定的一個位 int值。
int intValue()
將 Integer的值作為 int 。
long longValue()
返回此值 Integer為 long一個寬元轉換后。
static int lowestOneBit(int i)
在指定的 int值中,以最低位(最右邊)為1位返回一個最多為單個1位的 int值。
static int max(int a, int b)
返回兩個 int的較大值,就像調用 Math.max一樣 。
static int min(int a, int b)
返回兩個 int的較小值,就像調用 Math.min一樣 。
static int numberOfLeadingZeros(int i)
返回的最高階的(“最左邊的”)中所指定的二進制補碼表示的一個位前述零個比特的數量 int值。
static int numberOfTrailingZeros(int i)
返回零位以下最低階(“最右邊的”)的數量在指定的二進制補碼表示的一個位 int值。
static int parseInt(String s)
將字符串參數解析為帶符號的十進制整數。
static int parseInt(String s, int radix)
將字符串參數解析為第二個參數指定的基數中的有符號整數。
static int parseUnsignedInt(String s)
將字符串參數解析為無符號十進制整數。
static int parseUnsignedInt(String s, int radix)
將字符串參數解析為第二個參數指定的基數中的無符號整數。
static int remainderUnsigned(int dividend, int divisor)
返回無符號余數,將第一個參數除以秒,其中每個參數和結果被解釋為無符號值。
static int reverse(int i)
返回由指定的二進制補碼表示反轉位的順序而獲得的值 int值。
static int reverseBytes(int i)
返回反轉指定的二進制補碼表示的字節順序而獲得的值 int值。
static int rotateLeft(int i, int distance)
返回通過旋轉指定的二的補碼的二進制表示而得到的值 int由位指定數目的左值。
static int rotateRight(int i, int distance)
返回通過旋轉指定的二的補碼的二進制表示而得到的值 int右移位的指定數值。
short shortValue()
返回此值 Integer為 short的基本收縮轉換后。
static int signum(int i)
返回指定的 int值的 int函數。
static int sum(int a, int b)
根據+運算符將兩個整數相加。
static String toBinaryString(int i)
在基數2中返回整數參數的字符串表示形式為無符號整數。
static String toHexString(int i)
返回整數參數的字符串表示形式,作為16位中的無符號整數。
static String toOctalString(int i)
在基數8中返回整數參數的字符串表示形式為無符號整數。
String toString()
返回 String表示此對象 Integer的價值。
static String toString(int i)
返回一個 String指定整數的 String對象。
static String toString(int i, int radix)
返回由第二個參數指定的基數中的第一個參數的字符串表示形式。
static long toUnsignedLong(int x)
參數給轉換 long由無符號轉換。
static String toUnsignedString(int i)
將參數的字符串表示形式返回為無符號十進制值。
static String toUnsignedString(int i, int radix)
以第二個參數指定的基數中的無符號整數值返回第一個參數的字符串表示形式。
static Integer valueOf(int i)
返回一個 Integer指定的 int值的 Integer實例。
static Integer valueOf(String s)
返回一個 Integer對象,保存指定的值為 String 。
static Integer valueOf(String s, int radix)
返回一個 Integer對象,保存從指定的String中 String的值,當用第二個參數給出的基數進行解析時。

  4.1. byteValue()、shortValue()、intValue()、longValue()、floatValue()、doubleValue(),這些是繼承自 Number 類的方法,返回當前 Integer 對象對應 int 值對應的各種數據類型值(通過強制類型轉換,強轉到低精度時可能丟失數據)

  4.2. compareTo(Integer) 方法

    該方法接收一個被比較的 Integer 類對象,並與之比較大小,遵循 Comparable 接口的常規約定:若當前值等於參數值,返回 0;若當前值小於參數值,返回 -1;若當前值大於參數值,返回 1;

    public int compareTo(Integer anotherInteger) {
        return compare(this.value, anotherInteger.value);
    }

    /**
     * Compares two {@code int} values numerically.
     * The value returned is identical to what would be returned by:
     * <pre>
     *    Integer.valueOf(x).compareTo(Integer.valueOf(y))
     * </pre>
     *
     * @param  x the first {@code int} to compare
     * @param  y the second {@code int} 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(int x, int y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }

  4.3. decode(String),解碼方法,將參數字符串解碼得到 Integer,該方法自動識別正負符號和進制符號(如:0x、0、# 等),如 -0xa1 = -161,默認是 正數 和 十進制

    public static Integer decode(String nm) throws NumberFormatException {
        int radix = 10;
        int index = 0;
        boolean negative = false;
        Integer result;

        if (nm.length() == 0)
            throw new NumberFormatException("Zero length string");
        char firstChar = nm.charAt(0);
        // Handle sign, if present
        if (firstChar == '-') {
            negative = true;
            index++;
        } else if (firstChar == '+')
            index++;

        // Handle radix specifier, if present
        if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
            index += 2;
            radix = 16;
        }
        else if (nm.startsWith("#", index)) {
            index ++;
            radix = 16;
        }
        else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
            index ++;
            radix = 8;
        }

        if (nm.startsWith("-", index) || nm.startsWith("+", index))
            throw new NumberFormatException("Sign character in wrong position");

        try {
            result = Integer.valueOf(nm.substring(index), radix);
            result = negative ? Integer.valueOf(-result.intValue()) : result;
        } catch (NumberFormatException e) {
            // If number is Integer.MIN_VALUE, we'll end up here. The next line
            // handles this case, and causes any genuine format error to be
            // rethrown.
            String constant = negative ? ("-" + nm.substring(index))
                                       : nm.substring(index);
            result = Integer.valueOf(constant, radix);
        }
        return result;
    }

    可以看到,decode 方法首先對正負號和進制符號進行識別判斷,最后將剩下的純數值部分和得到的進制數值調用靜態工廠方法 valueOf(string, int) 構造 Integer 對象。

 

  4.4. valueOf 靜態方法

    Integer 類支持整型和字符串型參數的工廠方法,其中字符串型的工廠方法支持指定進制,並且會先使用 parseInt 方法解析出原始 int 數值,再通過 valueOf (int) 方法構造 Integer 對象。parseInt 方法就是遍歷字符串並使用進制值加權累加計算了。最值得注意的是 int 參數的 valueOf 方法,它體現了 Integer 類的緩存策略,后面單獨講。

    public static Integer valueOf(String s, int radix) throws NumberFormatException {
        return Integer.valueOf(parseInt(s,radix));
    }

    public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
    }

    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

  4.4. getInteger 方法

    該方法返回 string 參數指定的系統屬性值。支持指定默認值(通過第二個參數),若該屬性不存在或者不是 int 類型,則返回默認值

    public static Integer getInteger(String nm) {
        return getInteger(nm, null);
    }

    public static Integer getInteger(String nm, int val) {
        Integer result = getInteger(nm, null);
        return (result == null) ? Integer.valueOf(val) : result;
    }

    public static Integer getInteger(String nm, Integer val) {
        String v = null;
        try {
            v = System.getProperty(nm);
        } catch (IllegalArgumentException | NullPointerException e) {
        }
        if (v != null) {
            try {
                return Integer.decode(v);
            } catch (NumberFormatException e) {
            }
        }
        return val;
    }

  4.5. hashCode() 方法

    Integer 的 hashCode() 值就是它所保存的 int 型值。

/**
     * Returns a hash code for this {@code Integer}.
     *
     * @return  a hash code value for this object, equal to the
     *          primitive {@code int} value represented by this
     *          {@code Integer} object.
     */
    @Override
    public int hashCode() {
        return Integer.hashCode(value);
    }

    /**
     * Returns a hash code for a {@code int} value; compatible with
     * {@code Integer.hashCode()}.
     *
     * @param value the value to hash
     * @since 1.8
     *
     * @return a hash code value for a {@code int} value.
     */
    public static int hashCode(int value) {
        return value;
    }

  4.6. equals(Integer) 方法

    Integer 的 equals 方法比較的就是保存的 int 型值是否相等。很顯然,hashCode 和 equals 方法遵循散列的常規約定。

public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

 

5. Integer 的緩存機制

  前面學習 Boolean 類保存兩個對 true 和 false 值對象的靜態引用,使用 valueOf 構造對象時會始終返回其一。Integer 類也同樣使用了這種緩存機制。上文中提到了靜態工廠方法 valueOf(int) 使用了緩存策略,代碼中使用了 IntegerCache 類,那么我們就來看看該類源碼,這是 Integer 類的一個內部類,專門用於處理 Integer 緩存機制:

    

  可以看出,該類是私有內部類,開發者不可改變和初始化。該類通過靜態代碼塊在類加載的時候,循環創建 Integer 緩存對象,並創建索引表進行引用,需要時使用索引表快速獲取。緩存值范圍最小是 -128,最大默認是 127(可以使用虛擬機參數指定,虛擬機默認無該參數)。緩存對象值和所在索引表位置偏移量即是 127。

  再回頭看看 valueOf(int) 方法:當需要構造的 Integer 對象值在緩存范圍之內時,就從索引表查找緩存對象直接返回,否則構造新的對象返回。所以大家在開發中需要構建 Integer 對象時,推薦使用靜態工廠方法,少用 new 以節省開支。

    

 

 6. 總結

  6.1. Integer 是對 int 型的封裝數據類型,能表示的范圍是  -231 ~ 231-1 的所有整數;

  6.2. Integer 的 hashCode 值就是它所保存的 int 型值;

  6.3. Integer 提供了很多實用方法:min、max、sum、轉換成二/八/十六進制的字符串表示等;

  6.4. Integer 使用了對象緩存機制,默認范圍是  -128 ~ 127 ,推薦使用靜態工廠方法 valueOf 獲取對象實例,而不是 new,因為 valueOf 使用緩存,而 new 一定會創建新的對象分配新的內存空間;

 

【附】

  Integer 緩存機制驗證:https://www.cnblogs.com/coding-one/p/11389880.html

 


免責聲明!

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



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