问题是下面代码中各Swap函数的参数是传值还是传引用?
如果是传值:为什么在Swap4中修改传入参数会改变外部被传参数的值?
如果是传引用:为什么在Swap3中引已经被调换了,外部参数的引用还未变?
//: PassHandles.java
// Passing handles around
package c12;
public class PassHandles {
public static void main(String[] args) {
Complex c1=new Complex(1,1);
Complex c2=new Complex(2,2);
System.out.println("Before Swap"+c1.toString()+c2.toString());
Change.Swap1(c1,c2);
System.out.println("Swap1->"+c1.toString()+c2.toString());
Change ch=new Change();
ch.Swap2(c1,c2);
System.out.println("Swap2->"+c1.toString()+c2.toString());
ch.Swap3(c1,c2);
System.out.println("Swap3->"+c1.toString()+c2.toString());
ch.Swap4(c1,c2);
System.out.println("Swap4->"+c1.toString()+c2.toString());
}
} ///:~
class Change{
public static void Swap1(Object obj1,Object obj2){
Object obj=obj1;
obj1=obj2;
obj2=obj;
}
public void Swap2(Object obj1,Object obj2){
Object obj=obj1;
obj1=obj2;
obj2=obj;
}
public void Swap3(Complex c1,Complex c2){
Complex c=null;
c=c1;
c1=c2;
c2=c;
System.out.println("Inside Swap3->"+c1.toString()+c2.toString());
}
public void Swap4(Object obj1,Object obj2){
Complex c1=(Complex)obj1;
Complex c2=(Complex)obj2;
double tx=c1.real;
double ty=c1.imag;
c1.real=c2.real;
c1.imag=c2.imag;
c2.real=tx;
c2.imag=ty;
}
}
class Complex{
double real;
double imag;
public Complex(double _x,double _y){
real=_x;
imag=_y;
}
public String toString(){
return new String("("+real+"+"+imag+"i)");
}
public double Norm(){
return real*real-imag*imag;
}
public double Angle(){
return Math.acos(real/(this.Norm()));
}
}