怎样用静态函数交换两个对象-------急---
程序::::::
Employee a = new Employee("Alice",70000);
Employee b = new Employee("Bob",60000);
System.out.println("Before:a="+ a.getName());
System.out.println("Before:b="+ b.getName());
swap(a,b);
System.out.println("After:a="+ a.getName());
System.out.println("After:b="+ b.getName());
public static void swap(Employee x,Employee y)//SWAP方法的参数X和Y被初始化为两个对象引用的拷贝,这个方法
//交换的是这两个拷贝。
{
Employee temp = x;
x = y;
y = temp;
System.out.println("End of method: x = "+x.getName());
System.out.println("End of method: y = "+y.getName());
}
-----------------------
结果:
Testing swap
Before:a=Alice
Before:b=Bob
End of method: x = Bob
End of method: y = Alice
After:a=Alice
After:b=Bob
--------------------------
书上说是交换能的结果未保留下来,所以我想请问各位大侠 ,怎样才能保留交换的结果啊
------解决方案--------------------public static void swap(Employee x,Employee y)
{
temp.name = x.name; temp.number = x.number; // 就是这个意思!
x.name = y.name; x.number = y.number; // 自己改改吧~
y.name = temp.name; y.number = temp.number ;//
System.out.println( "End of method: x = "+x.getName());
System.out.println( "End of method: y = "+y.getName());
}
------解决方案--------------------class Swap
{
public static void main(String[] argc)
{
Employee a = new Employee( "Alice ",70000);
Employee b = new Employee( "Bob ",60000);
System.out.println( "Before:a= "+ a.getName());
System.out.println( "Before:b= "+ b.getName());
swap(a,b);
System.out.println( "After:a= "+ a.getName());
System.out.println( "After:b= "+ b.getName());
}
public static void swap(Employee a,Employee b)
{
String name = a.getName();
int salary=a.getSalary();
a.setName(b.getName());
a.setSalary(b.getSalary());
b.setName(name);
b.setSalary(salary);
System.out.println( "End of method: x = "+a.getName());
System.out.println( "End of method: y = "+b.getName());
}
}
class Employee
{
String name;
int salary;
Employee(String name,int salary)
{
this.name=name;
this.salary=salary;
}
String getName()
{
return name;
}
void setName(String name)
{
this.name=name;
}
int getSalary()
{
return salary;
}
void setSalary(int salary)
{
this.salary=salary;
}
}
这样才行