首先,先探討一下Java 的傳參數的概念,上述提及Java只有Call by value[1][2],以下用個簡單的例子說明
Sample1 :
public static void main(String[] args){
int a1 = 5;
int[] a2 = new int[1];
System.out.println("a1 value = " + a1);
System.out.println("a2 value = " + a2);
}
int a1 = 5;
int[] a2 = new int[1];
System.out.println("a1 value = " + a1);
System.out.println("a2 value = " + a2);
}
Output :
a1 value = 5
a2 value = [I@3771ed5e
a2 value = [I@3771ed5e
Java本身並無指標的概念,所以變數只會儲存Value,如a1是存儲存5,而a2則是存儲address value(也是Value)。故以這樣的概念,只要call by value的value是address,那就可以達成如C/C++的操作,以下提供兩種方式來達成多變數回傳。
Sample2: 陣列法
陣列法缺點在於,陣列大小必須在外層就決定,無法從內層決定,故如果必須從內層決定,那只能用物件法。
public static void swap(int[] a, int[] b) {
int tmp = 0;
tmp = a[0];
a[0] = b[0];
b[0] = tmp;
}
public static void main(String[] args){
int[] a = {1};
int[] b = {2};
swap(a,b);
System.out.println("a value = " + a[0] );
System.out.println("b value = " + b[0] );
}
int tmp = 0;
tmp = a[0];
a[0] = b[0];
b[0] = tmp;
}
public static void main(String[] args){
int[] a = {1};
int[] b = {2};
swap(a,b);
System.out.println("a value = " + a[0] );
System.out.println("b value = " + b[0] );
}
Sample3: 物件法(也是傳address方式)
public class SampleRef {
int x;
public SampleRef(int x) {
this.x = x;
}
public static void swap(SampleRef a, SampleRef b) {
int tmp = 0 ;
tmp = a.x;
a.x = b.x;
b.x = tmp;
}
public static void main(String[] args){
SampleRef a = new SampleRef(1);
SampleRef b = new SampleRef(2);
swap(a,b);
System.out.println("a value = " + a.x );
System.out.println("b value = " + b.x );
}
}
int x;
public SampleRef(int x) {
this.x = x;
}
public static void swap(SampleRef a, SampleRef b) {
int tmp = 0 ;
tmp = a.x;
a.x = b.x;
b.x = tmp;
}
public static void main(String[] args){
SampleRef a = new SampleRef(1);
SampleRef b = new SampleRef(2);
swap(a,b);
System.out.println("a value = " + a.x );
System.out.println("b value = " + b.x );
}
}
Reference
[1] Java沒有指標? - 淺談參考(Reference)與物件的複製(Object copy)
[2] 獅子的鬃毛--Java 的物件傳遞是 Call By Reference
[3] How do I pass a primitive data type by reference
沒有留言:
張貼留言