現在剛開始學習java。今天寫一個swap,讓我對java沒有指針這個事情深有體會。
由於我想是把swap()當成一個函數來寫,因此我嘗試這樣的方式。
private static void swap(int &a, int &b){ int temp = a; a = b; b = temp; }
我發現在eclipse中是有錯誤的,java中的參數傳遞都是采用值傳遞的傳遞方式,因此不能使用引用符號。
后面我發現可以使用重新賦值的方法:
private static int[] swap(int a, int b){ int temp = a; a = b; b = temp; return new int[]{a,b}; } //下面是主函數的實現 public static void main{ int a = 4; int b = 6; int[] swap = swap(a,b); a = swap[0]; b = swap[1]; System.out.print(a + " "); System.out.print(b); }
但是我覺得使用這樣的方式還是有點惱火,畢竟比較麻煩。於是我想到了外部內聯的方式。
public class TestSwap { public static void main(String[] args){ Exchange exc = new Exchange(2,3); exc.swap(exc); System.out.print(exc.i); } } class Exchange{ int i , j; Exchange(int i, int j){ this.i = i; this.j = j; } public void swap(Exchange exc){ int temp = exc.i; exc.i = exc.j; exc.j = temp; } }
使用這種方式能夠簡單的簡明的實現這種方式。
通過這個簡單的函數認識了java語言的特性。