程序员都知道,在C/C++里面交换值的方法:java
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开始。 this
2.也能够经过从新定义个类(在Java中咱们能够经过使用int的包装类——integer,而后将其做为值得引用传到函数中,但这个integer包装类也不容许你来改变它的数据域;但这不妨碍咱们用本身的包装类,好比说下面实现的MyInteger():spa
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; } }