【源碼】java封裝類總結,源碼java封裝

來源:互聯網
上載者:User

【源碼】java封裝類總結,源碼java封裝

1.封裝類除了Void和Character,其他六個全部都繼承自Number。Number是一個抽象類別。如下:

public abstract class Number implements java.io.Serializable {    public abstract int intValue();    public abstract long longValue();    public abstract float floatValue();    public abstract double doubleValue();    public byte byteValue() {        return (byte)intValue();    }    public short shortValue() {        return (short)intValue();    }    private static final long serialVersionUID = -8742448824652078965L;}

2.Integer、Byte、Short、Long內部都有"緩衝"靜態類,以Integer為例:緩衝即一個Integer數組,預設大小為-128~127。初始化時,會new出256個Integer對象存在此數組中。
 private static class IntegerCache {        static final int low = -128;        static final int high;        static final Integer cache[];        static {            int h = 127;            String integerCacheHighPropValue =                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");            if (integerCacheHighPropValue != null) {                int i = parseInt(integerCacheHighPropValue);                i = Math.max(i, 127);                // Maximum array size is Integer.MAX_VALUE                h = Math.min(i, Integer.MAX_VALUE - (-low));            }            high = h;            cache = new Integer[(high - low) + 1];            int j = low;            for(int k = 0; k < cache.length; k++)                cache[k] = new Integer(j++);        }        private IntegerCache() {}    }

當調用Integer.valueOf方法時,會首先判斷參數是否在緩衝範圍內,若在,直接返回緩衝對象,否則,構造之。

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

可見,Integer將載入緩衝數組延遲到了最晚,避免浪費空間。另外可以通過intValue方法返回Integer對應的int值(其他封裝類類似):
 public int intValue() {        return value;    }

value是Integer成員變數,構造時被傳遞進來:

 private final int value;    public Integer(int value) {        this.value = value;    }    public Integer(String s) throws NumberFormatException {        this.value = parseInt(s, 10);    }
3.除了Void類,其餘封裝類均實現了Comparable介面,可以通過compareTo方法比較兩個封裝類的大小。同時封裝類提供了靜態compare方法比較兩個參數的大小(以Integer為例):
 public int compareTo(Integer anotherInteger) {        return compare(this.value, anotherInteger.value);    }

compareTo方法其實調用了compare靜態方法:
public static int compare(int x, int y) {        return (x < y) ? -1 : ((x == y) ? 0 : 1);    }
4.Integer的getInteger方法的作用是返回具有指定名稱的系統屬性的整數值,不要誤用。
public static Integer getInteger(String nm, Integer val) {        String v = null;        try {            v = System.getProperty(nm);        } catch (IllegalArgumentException e) {        } catch (NullPointerException e) {        }        if (v != null) {            try {                return Integer.decode(v);            } catch (NumberFormatException e) {            }        }        return val;    }

5.封裝類的toString方法經過了重寫
public static String toString(int i) {        if (i == Integer.MIN_VALUE)            return "-2147483648";        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);        char[] buf = new char[size];        getChars(i, size, buf);        return new String(buf, true);    }public String toString() {        return toString(value);    }

6.可以使用parseXXX方法將字串轉化為對應的數字。
public static int parseInt(String s, int radix)                throws NumberFormatException    {        /*         * WARNING: This method may be invoked early during VM initialization         * before IntegerCache is initialized. Care must be taken to not use         * the valueOf method.         */        if (s == null) {            throw new NumberFormatException("null");        }        if (radix < Character.MIN_RADIX) {            throw new NumberFormatException("radix " + radix +                                            " less than Character.MIN_RADIX");        }        if (radix > Character.MAX_RADIX) {            throw new NumberFormatException("radix " + radix +                                            " greater than Character.MAX_RADIX");        }        int result = 0;        boolean negative = false;        int i = 0, len = s.length();        int limit = -Integer.MAX_VALUE;        int multmin;        int digit;        if (len > 0) {            char firstChar = s.charAt(0);            if (firstChar < '0') { // Possible leading "+" or "-"                if (firstChar == '-') {                    negative = true;                    limit = Integer.MIN_VALUE;                } else if (firstChar != '+')                    throw NumberFormatException.forInputString(s);                if (len == 1) // Cannot have lone "+" or "-"                    throw NumberFormatException.forInputString(s);                i++;            }            multmin = limit / radix;            while (i < len) {                // Accumulating negatively avoids surprises near MAX_VALUE                digit = Character.digit(s.charAt(i++),radix);                if (digit < 0) {                    throw NumberFormatException.forInputString(s);                }                if (result < multmin) {                    throw NumberFormatException.forInputString(s);                }                result *= radix;                if (result < limit + digit) {                    throw NumberFormatException.forInputString(s);                }                result -= digit;            }        } else {            throw NumberFormatException.forInputString(s);        }        return negative ? result : -result;    } public static int parseInt(String s) throws NumberFormatException {        return parseInt(s,10);    }





java封裝類問題

==是用來比較兩個基礎資料型別 (Elementary Data Type)的變數值是否相等,==也用於判斷兩個對象引用名稱是否參考至同一個對象。在自動裝箱時對於值從–128到127之間的值,它們被裝箱為Integer對象後,會存在記憶體中被重用(就是說記憶體指向相同)。
所以造成 System.out.println(i1==i2); 輸出true

如果超過了從–128到127之間的值,被裝箱後的Integer對象並

不會被重用(指向了新的記憶體位址),即相當於每次裝箱時都建立一個Integer對象
所以System.out.println(i3==i4); 輸出false

總結:–128到127之間的值記憶體空間引用的是同一個地址,超出則存在新的記憶體空間
 
java封裝類

是的,凡是你能點出來的方法,都是java已經在jar包中封裝好的方法,你直接使用即可。
java開源,你如果想看原始碼的話,可以按住ctrl鍵,滑鼠懸浮在對應的方法上,點進去看即可;
如果是介面,依上述方法操作可以看到兩個選項,一個是Open Declaration 和Open Implementation,前者是介面定義,後者是介面實現,這個你可以點在System.out.println(i)中的println()方法上自己實驗一下
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.