值傳遞&引用傳遞 經典題目

public static void main(String [] args){
Integer a=1,b=2;

System.out.println("a = " + a +",b = " + b);

swap1(a,b);

System.out.println("a = " + a +",b = " + b);
}

版本1
public static void swap1(Integer a,Integer b){
Integer temp=b;
b=a;
a=temp;
}


如果傳值是基本值,傳的是原始值的副本
函數中修改,只是修改了副本,原始值不變

如果傳的引用值,則是原始值的地址

怎麼做?

Integer源碼
/**
* The value of the {@code Integer}.
*
* @serial
*/
private final int value;

修改這個成員變量的值,修改地址


版本2
public static void swap2(Integer a,Integer b) throws Exception{
Field field = Integer.class.getDeclaredField("value"); //通過反射拿到成員變量
field.setAccessible(true); //設置訪問權限 訪問私有變量
int temp = a.intValue();
field.set(a,b.intValue());
field.set(b,temp);
}

爲什麼還是沒有達到預期的效果???抓狂  a和b的值還是沒有交換 驚恐 

field.set(a,b.intValue()); //這句話改變了a,也改變了temp
temp和a用的一塊內存地址,a改了temp也改了


Integer -128 - 127會有緩存
/**
* 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() {}
}


驗證緩存的存在
public static void main(String [] args)throws Exception{
Integer a=1,b=1;

System.out.println(a==b);

}



返回true則說明是a,b在同一塊地址


版本3
public static void swap3(Integer a,Integer b) throws Exception{
Field field = Integer.class.getDeclaredField("value"); //通過反射拿到成員變量
field.setAccessible(true); //設置訪問權限 訪問私有變量
Integer temp = new Integer(a.intValue()); //修改 new Integer對象 開闢新空間
field.set(a,b.intValue());
field.set(b,temp);
}

考點:
1,值傳遞與引用傳遞
2,自動裝箱與拆箱
3,Integer -128 - 127 有cache
4,通過反射修改private final成員變量(注意修改訪問權限)


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