Java实现交换两个数的方法
Java中不能直接操作指针变量,使用基本类型传参的时候都是值传递,也就是传入方法的只是原来变量的一个副本,所以在方法中交换是副本,并达不到交换的目的。
但是可以通过以下方法来实现swap()方法
-
数组
public class Test01 { public static void main(String[] args) { int[] arr = {1, 2, 3}; System.out.print("arr[0] = " + arr[0]); System.out.println(" arr[1] = " + arr[1]); Test01 t1 = new Test01(); //通过传入数组 交换数组中下标为0和下标为1的两个数 t1.swap(arr, 0, 1); System.out.print("arr[0] = " + arr[0]); System.out.println(" arr[1] = " + arr[1]); } //通过传入数组 交换数组中下标为i与下标为j的两个数 public void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
-
使用类变量(改变两个数的值)
public class Test02 { static int a = 2; static int b = 3; public static void main(String[] args) { System.out.println("a = " + a + " " + "b = " + b); swap(); System.out.println("a = " + a + " " + "b = " + b); } public static void swap() { int temp = a; a = b; b = temp; } }
-
外部内联
public class Test03 { public static void main(String[] args) { Exchange exc = new Exchange(1, 2); exc.swap(exc); System.out.println("i = " + exc.i +" " + "j = "+ exc.j); } } class Exchange { int i; int j; public 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; } }
-
包装类(Integer包装类也不允许你来改变它的数据域,但是可以实现自己MyInteger)
public class Test05 { //传对象引用 public void swap(MyInteger m1, MyInteger m2) { int temp = m1.getValue(); //temp = m1.i; m1.setValue(m2.getValue()); //m1.i = m2.i; m2.setValue(temp); //m2.i = temp; } public static void main(String[] args) { int a = 2; int b = 3; System.out.println("a = " + a + " " + "b = " + b); Test05 t5 = new Test05(); MyInteger m1 = new MyInteger(a); MyInteger m2 = new MyInteger(b); t5.swap(m1, m2); a = m1.getValue(); b = m2.getValue(); System.out.println("a = " + a + " " + "b = " + b); } } class MyInteger { private int i; public MyInteger(int i) { this.i = i; } public int getValue() { return this.i; } public void setValue(int i){ this.i = i; } }