62,614
社区成员
发帖
与我相关
我的任务
分享
/**
* In Java, the primitive parameters are the copy values, didn't change the original values by this way.
* @param x
* @param y
*/
public static void swap1(int x, int y){
int temp = y;
y=x;
x=temp;
}
int x =5, y =6;
swap1(x,y);
System.out.println("x="+x);
System.out.println("y="+y);
class myInteger {
private int value;
public myInteger(int x){ value = x;}
public int getValue(){ return value; }
public void insertValue(int x){ value = x; }
}
/**
* In Java, actually we can use wrapper objects as parameter, by this way, it will pass the address of the object.
* But Integer can't be changed a value, so we overload the default Integer class.
* @param x
* @param y
*/
public static void swap3(myInteger x, myInteger y){
int temp = y.getValue();
y.insertValue(x.getValue());
x.insertValue(temp);
}
myInteger xI = new myInteger(x);
myInteger yI = new myInteger(y);
swap3(xI, yI);
System.out.println("x=" + xI.getValue());
System.out.println("y=" + yI.getValue());
/**
*
* @param a - array, will pass the first element address of this array
* @param x - position of this array, not value
* @param y - position of this array, not value
*/
public static void swap2(int[] a, int x, int y)
{
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
int[] a = new int[2];
a[0] = x;
a[1] = y;
swap2(a, 0, 1);
System.out.println("x=" + a[0]);
System.out.println("y=" + a[1]);
class Test{
int x ;
int y ;
}
public class Main {
public static void main(String args[]){
Test t = new Test();
t.x = 3 ;
t.y = 4 ;
swap(t);
//swap(t,t.x,t.y);
System.out.println(t.x+","+t.y);
}
public static void swap(Test t) {
t.x = t.x+t.y ;
t.y = t.x - t.y ;
t.x = t.x - t.y ;
}
public static void swap(Test t, int x, int y) {
t.x = x + y;
t.y = t.x - y ;
t.x = t.x - x ;
}
//其实传对象和传数组的方法类似
}List<Integer> l = Arrays.asList(x, y);
System.out.println("x="+ l.get(0).intValue());
System.out.println("y="+ l.get(1).intValue());
Collections.swap(l, 0, 1);
System.out.println("x="+ l.get(0).intValue());
System.out.println("y="+ l.get(1).intValue());