我有如下代码,其中我在Instance variables
中交换类的Function
称为SwapNames
public class Sam3
{
public String FirstName, LastName;
public static void main(String[] args)
{
Sam3 objSam1 = new Sam3();
Sam3 objSam2 = new Sam3();
objSam1.FirstName = "Name1";
objSam2.LastName = "Name2";
System.out.print(objSam1.FirstName + " " + objSam2.LastName);
SwapNames(objSam1, objSam2);
System.out.print(objSam1.FirstName + " " + objSam2.LastName);
}
public static void SwapNames(Sam3 obj1, Sam3 obj2)
{
Sam3 temp = obj2;
obj2 = obj1;
obj1 = temp;
obj1.FirstName = "First Name";
obj2.LastName = "Last Name";
}
}
现在代码的输出如下
Name1 Name2
Name1 Name2
我不明白的是我交换了
obj1 and obj2
中的值-对它们的classes
的引用。之后,我更改了值。为什么代码没有生效。
谢谢您的回复
最佳答案
public static void SwapNames(Sam3 obj1, Sam3 obj2)
{
Sam3 temp = obj2;
obj2 = obj1;
obj1 = temp;
obj1.FirstName = "First Name"; //<-- is actually objSam2
obj2.LastName = "Last Name"; //<-- is actually objSam1
}
看看发生了什么事:
class Test{
public int i=2;
}
public class Main {
public static void main(String[] args) {
Test t1 = new Test();
t1.i=0;
Test t2 = new Test();
t2.i=1;
System.out.println(t1.i+" "+t1);
System.out.println(t2.i+" "+t2);
test(t1,t2);
System.out.println(t1.i+" "+t1);
System.out.println(t2.i+" "+t2);
}
public static void test(Test a, Test b){
Test swap=a;
a=b;
b=swap;
System.out.println(a.i+" "+a);
System.out.println(b.i+" "+b);
}
}
/*
output:
0 Test@3c56b64c
1 Test@60da5686
1 Test@60da5686
0 Test@3c56b64c
0 Test@3c56b64c
1 Test@60da5686
*/