假设我们有一个名为“car”的类,它具有一些属性。我们创建了car的两个对象,car1和car2,如何交换car1和car2的数据?
一个简单的解决方案是交换成员。例如,如果类car只有一个integer(整数)属性“no”(car number),我们可以通过简单地交换两辆车的成员来交换汽车。
class car { int no; car(int no) { this.no = no; } } class main { public static void swap(car c1, car c2) { int temp = c1.no; c1.no = c2.no; c2.no = temp; } public static void main(string[] args) { car c1 = new car(1); car c2 = new car(2); swap(c1, c2); system.out.println("c1.no = " + c1.no); system.out.println("c2.no = " + c2.no); } }
输出:
c1.no = 2c2.no = 1
如果我们不知道car的成员呢?
上面的解决方案是有效的,因为我们知道car中有一个成员“no”。如果我们不知道car的成员或者成员列表太大怎么办。这是一种非常常见的情况,因为使用其他类的类可能无法访问其他类的成员。下面的解决方案有效吗?
class car { int model, no; car(int model, int no) { this.model = model; this.no = no; } void print() { system.out.println("no = " + no + ", model = " + model); } } class main { public static void swap(car c1, car c2) { car temp = c1; c1 = c2; c2 = temp; } 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 = 101no = 2, model = 202
从上面的输出中我们可以看到,没有交换对象。参数在java中是通过值传递的。因此,当我们将c1和c2传递给swap()时,swap()函数会创建这些引用的副本。
解决方案是使用wrapper类如果我们创建一个包含car引用的包装类,我们可以通过交换wrapper类的引用来交换car。
class car { int model, no; car(int model, int no) { this.model = model; this.no = no; } void print() { system.out.println("no = " + no + ", model = " + model); } } class carwrapper { car c; carwrapper(car c) {this.c = c;} } class main { public static void swap(carwrapper cw1, carwrapper cw2) { car temp = cw1.c; cw1.c = cw2.c; cw2.c = temp; } 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 = 202no = 1, model = 101
因此,即使user 类无法访问要交换对象的类的成员,wrapper类解决方案仍然有效。
相关推荐:《java教程》
本篇文章就是关于java交换对象的方法介绍,希望对需要的朋友有所帮助!
以上就是如何在java中交换对象数据?(代码实例)的详细内容。