程序員都知道,在C/C++里面交換值的方法:
void swap(int &a,int &b) { int temp; temp=a; a=b; b=temp; }
但是在Java中這種方法是行不通的,因為Java對普通類型的變量是不支持引用傳遞的。
怎么辦呢?
1.可以像下面這樣通過傳數組(也屬於傳值)的方法來完成交換(很多排序算法就是這樣實現)。
public static void swap(int[] data,int a,int b){ int temp=data[a]; data[a]=data[b]; data[b]=temp; }
package pkg2020華南虎; /** * * @author yl */ public class SwapValue { public static void main(String[] args) { SwapValue sv = new SwapValue(); int[] num = new int[2]; num[0] = 20; num[1] = 30; sv.swap(num, 0, 1); System.out.println("num1,num2:" + num[0] + "," + num[1]); } public static void swap(int[] data, int a, int b) { int temp = data[a]; data[a] = data[b]; data[b] = temp; } }
或者
package pkg2020華南虎; /** * * @author yl */ public class SwapValue { public static void main(String[] args) { int[] num = new int[2]; num[0] = 20; num[1] = 30; swap(num, 0, 1); System.out.println("num1,num2:" + num[0] + "," + num[1]); } public static void swap(int[] data, int a, int b) { int temp = data[a]; data[a] = data[b]; data[b] = temp; } }
注意:數組排序從0開始。
2.也可以通過重新定義個類(在Java中我們可以通過使用int的包裝類——integer,然后將其作為值得引用傳到函數中,但這個integer包裝類也不允許你來改變它的數據域;但這不妨礙我們用自己的包裝類,比如說下面實現的MyInteger():
package pkg2020華南虎; /** * * @author yl */ //MyInteger:於Integer類似,但是其對象可以變值 class MyInteger { private int x;//將x作為唯一的數據成員 public MyInteger(int xIn) { x = xIn; }//構造器 public int getValue() { return x; }//得到值 public void insertValue(int xIn) { x = xIn; }//改變值 } public class SwapValue02 { static void swap(MyInteger xWrap, MyInteger yWrap) { int temp = xWrap.getValue(); xWrap.insertValue(yWrap.getValue()); yWrap.insertValue(temp); } public static void main(String[] args) { int a = 23, b = 25; MyInteger aWrap = new MyInteger(a); MyInteger bWrap = new MyInteger(b); swap(aWrap, bWrap); a = aWrap.getValue(); b = bWrap.getValue(); System.out.println("a,b is: " + a + "," + b); } }
3.由於Java中的參數傳遞都是采用的值傳遞方式,這不妨礙我們用swap的時候采用外部內聯的方式:
package pkg2020華南虎; /** * * @author yl */ public class SwapValue03 { int i, j; public static void main(String[] args) { SwapValue03 sv = new SwapValue03(1, 2); sv.swap(); System.out.println("i,j =" + sv.i + "," + sv.j); } public SwapValue03(int i, int j) {//構造方法 this.i = i; this.j = j; } public void swap() { int temp = i; i = j; j = temp; } }