java 中的参数传递都是采用的值传递方式,所以在用swap的时候,可以采用外部内联的方式:
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;
}
}
实质就是在进行交换的时候,swap方法不能带有参数,如果带有参数的话,实际并没有发生交换:
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);
}
}
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;
}
}
实质就是在进行交换的时候,swap方法不能带有参数,如果带有参数的话,实际并没有发生交换:
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);
}
}