Java如何交换两个对象
转载:/swap-exchange-objects-java/
假设我们有一个叫Car的类,这个类中也有一些属性。我们创建Car类的两个对象,一个叫car1,另一个叫car2,那如何交换car1与car2的数据呢?
交换成员:例如,如果这个Car类只有一个整型的车号,我们可以通过交换两个车的号码来交换两个车。
// A Java program to demonstrate that we can swap two
// objects be swapping members.
// A car with number class Car
class Car
{
int no;
Car(int no) { this.no = no; }
}
// A class that uses Car objects
class Main
{
// To swap c1 and c2
public static void swap(Car c1, Car c2)
{
int temp = c1.no;
c1.no = c2.no;
c2.no = temp;
}
// Driver method
public static void main(String[] args)
{
Car c1 = new Car(1);
Car c2 = new Car(2);
swap(c1, c2);
System.out.println(" = " + c1.no);
System.out.println(" = " + c2.no);
}
}
输出:
c1.no = 2
c2.no = 1
如果我们不知道类的成员呢?
以上方法只能是在我们直到车号这个成员的时候才能使用,如果我们不知道Car的成员或者说成员列表太多了,那咋办?这是一个十分常见的情况,一个类用到其他的类,但是又不能访问这个类的成员。看看下面这段代码能不能搞定?
// A Java program to demonstrate that simply swapping
// object references doesn't work
// A car with number and name
class Car
{
int model, no;
// Constructor
Car(int model, int no)
{
this.model = model;
this.no = no;
}
// Utility method to print Car
void print()
{
System.out.println("no = " + no +
", model = " + model);
}
}
// A class that uses Car
class Main
{
// swap() doesn't swap c1 and c2
public static void swap(Car c1, Car c2)
{
Car temp = c1;
c1 = c2;
c2 = temp;
}
// Driver method
public static void main(String[] args)
{
Car c1 = new Car(101, 1);
Car c2 = new Car(202, 2);
swap(c1, c2);
c1.print();
c2.print();
}
}
输出:
no = 1, model = 101
no = 2, model = 202
从上面的输出可以看出,对象没有交换成功。我们在前面一章讨论过在Java中参数的传递。所以当我们传给swap方法c1与c2的时候,这个方法就创建了这两个引用的副本。
用封装类(Wrapper Class)解决,如果我们建立一个封装类,这个类包含Car的引用,我们可以通过交换封装类的引用来交换这两个car。
// A Java program to demonstrate that we can use wrapper
// classes to swap to objects
// A car with model and no.
class Car
{
int model, no;
// Constructor
Car(int model, int no)
{
this.model = model;
this.no = no;
}
// Utility method to print object details
void print()
{
System.out.println("no = " + no +
", model = " + model);
}
}
// A Wrapper over class that is used for swapping
class CarWrapper
{
Car c;
// Constructor
CarWrapper(Car c) {this.c = c;}
}
// A Class that use Car and swaps objects of Car
// using CarWrapper
class Main
{
// This method swaps car objects in wrappers
// cw1 and cw2
public static void swap(CarWrapper cw1,
CarWrapper cw2)
{
Car temp = cw1.c;
cw1.c = cw2.c;
cw2.c = temp;
}
// Driver method
public static void main(String[] args)
{
Car c1 = new Car(101, 1);
Car c2 = new Car(202, 2);
CarWrapper cw1 = new CarWrapper(c1);
CarWrapper cw2 = new CarWrapper(c2);
swap(cw1, cw2);
cw1.c.print();
cw2.c.print();
}
}
输出:
no = 2, model = 202
no = 1, model = 101
所以如果用户类不能访问到被交换的类的成员的时候,封装类可以解决这个问题。