在C/C++里面交换值的方法:
1 2 3 4 5 6 7 8 | [cpp] view plaincopyprint?void swap( int &a , int &b) { int temp; temp = a; a = b; b = temp; } |
但在JAVA中用这种方法是行不通的,因为“Java对普通类型的变量是不支持引用传递的”。
怎么办呢?
1. 可以像下面这样通过传数组(也属于传值)的方法来完成对换(在很多排序算法里面就是这么干的):
1 2 3 4 5 6 | [java] view plaincopyprint?public static void swap( int [] data, int a, int b) { int t = data[a]; data[a] = data[b]; data[b] = t; } |
2. 也可以通过重新定义个类(在JAVA中我们可以通过使用int的包装类---Integer,然后将其作为值的引用传到函数中,但这个Integer包装类也不允许你来改变它的数据域;但这不防碍我们用自己的包装类,比如说下面实现的MyInteger):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | //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 Swapping { // swap: 传对象引用 static void swap(MyInteger rWrap, MyInteger sWrap) { // 变值过程 int t = rWrap.getValue(); rWrap.insertValue(sWrap.getValue()); sWrap.insertValue(t); } public static void main(String[] args) { int a = 23 , b = 47 ; System.out.println( "Before. a:" + a + ", b: " + b); MyInteger aWrap = new MyInteger(a); MyInteger bWrap = new MyInteger(b); swap(aWrap, bWrap); a = aWrap.getValue(); b = bWrap.getValue(); System.out.println( "After. a:" + a + ", b: " + b); } } |
3. 由于java 中的参数传递都是采用的值传递方式,这不防碍我们用swap的时候采用外部内联的方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | [java] view plaincopyprint?public class Swap2 { public static void main(String args[]){ Swap2 sw = new Swap2( 1 , 2 ); System.out.println( "i is" + sw.i); System.out.println( "j is" + sw.j); sw.swap(); System.out.println( "i is" + sw.i); System.out.println( "j is" + sw.j); } int i,j; public Swap2( int i, int j){ this .i = i; this .j = j; } public void swap(){ int temp; temp = i; i = j; j = temp; } } public class Swap1 { public static void Swap1(Integer a, Integer b){ Integer temp = a; a = b; b = temp; } public static void main(String args[]){ Integer a,b; a = new Integer( 10 ); b = new Integer( 20 ); Swap1.Swap1(a, b); System.out.println( "a is " + a); System.out.println( "b is " + b); } } |
转载于: xc145214