值传递和引用传递
分析一道不太简单的题:
使用 Integer 进行元素的交换的时候,两个本身的值并没有真正的交换
package com.zwz.test;
/**
* 两个 Integer 的引用对象传递给一个 swap 的方法内部进行交换,
* 返回后,两个引用值是否会发生变化
*/
public class TestInteger
{
public static void main(String[] args) {
Integer a=1,b=2;
System.out.println( "a="+a+" b="+b );
swap( a,b );
System.out.println( "a="+a+" b="+b );
}
public static void swap( Integer i1,Integer i2 ){
Integer temp = i1;
i1 = i2;
i2 = temp;
}
}
结果是交换后数据并没有发生变化
原因在于传值的时候是进行的值的传递,并没有把引用传递进来,所以交换后原始引用值并没有发生变化。
把方法进行下面的修改:
public static void swap2( Integer i1,Integer i2 ) throws Exception {
Field field = Integer.class.getDeclaredField("value");
field.setAccessible( true );
int tmp = i1.intValue();
field.set( i1,i2.intValue() );
field.set( i2,tmp );
}
使用上面的这个 swap2 返回的结果是
a=2 b=2 因为 Integer.intValue() 这个函数获取的是 Cache 缓存当中的数据
先把 i1的值给 tmp tmp值变为 1
然后 i2的值给 i1 , 这时候 tmp也用的是 i1的缓存 ,所以值都变成2
最后再把 tmp的值给i2 , i2 也变成 2
如果想让 i1 与 i2 真正的交换值,需要这样写:
public static void swap2( Integer i1,Integer i2 ) throws Exception {
Field field = Integer.class.getDeclaredField("value");
field.setAccessible( true );
Integer tmp = new Integer( i1.intValue() );
field.set( i1,i2.intValue() );
field.set( i2,tmp );
}
还没有评论,来说两句吧...