Java String 到底是引用傳遞還是值傳遞?

對於非對象類型,java 參數傳遞都是值傳遞, 比如int.
java 會直接複製一份值到方法參數裏面去使用。

而對於對象類型,其實也是值傳遞,java 參數傳遞值的是對象的引用,相當於對象在堆裏面的內存地址。

我們分析下以下代碼:

public class StringTransactTest {

    public static void main(String[] args) {
        String a = "a";
        String b = new String("b");

        changeString(a);
        changeString(b);

        System.out.println(a);
        System.out.println(b);
        //輸出是a b  因爲調用changeString 的時候,我們傳遞的是String 對象在
//        內存中的應用,調用changeString方法的時候,會複製一份引用的值到參數棧裏面,
//        在changeString方法裏面,changeString 的參數變量又被重新賦值爲另一個string 對象,
//        方法結束,方法外面的變量a指向的內存地址一直都沒有改變過,所以,打印出來還是a.

        int number = 23;
        changeNum(number);
        System.out.println(number);
//        打印是23,因爲java 是值傳遞,基本數據類型會複製一份到方法棧中,在方法裏面改變局部變量的值
// 不會影響外面的值。

        int number1 = 10;
        Integer integer11 = 10;
        Integer integer12 = 10;


        System.out.println(number1 == integer11);
        System.out.println(integer11 == integer12);
        //第一個是true number1 是基本數據類型,而integer11 是對象類型。他們兩個比較的時候,
//        會發生自動拆箱,integer11 拆箱之後爲基本數據類型,然後比較,肯定是相等的。
//    第二個是true 是因爲Integer  直接這樣寫,相當於Integer.valueOf(),而這個類有緩存機制的。
//     -127-128之間的數字會被緩存   當是同一個數字的時候,會直接返回同一個對象,所以,兩個比較是true

        int number2 = 1000;
        Integer integer21 = 1000;
        Integer integer22 = 1000;

        System.out.println(number2 == integer21);
        System.out.println(integer21 == integer22);

        //第一個是true 和上面一樣
//    第二個是false 是因爲Integer  是因爲1000已經超過了默認的緩存機制,就會去new 對象,new 的兩個對象肯定會相當。

        Integer integer31 = new Integer(1000);
        Integer integer32 = new Integer(1000);
        System.out.println(integer31 == integer32);
        //兩個new 的對象,在堆分配了不同的內存,所以內存地址不同 false

    }

    private static void changeString(String a) {
        a = new String("changed");
    }

    private static void changeNum(int number){
        number = 20;
    }

}

關於Interger 的緩存機制,我們直接上源碼:

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


我們看到,如果值在low 和 high 之間,那麼會從緩存數組裏面,直接返回,否則就調用new 方法。

    /**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

這個就是Integer 的緩存。默認是-127 到 128之間,初始化的時候會直接for 循環創建這些對象,使用的時候,就可以直接用了。

參考:https://blog.csdn.net/losetowin/article/details/49968365

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章