public void swap(Point var1, Point var2)
{
var1.x = 100;
var1.y = 100;
Point temp = var1;
var1 = var2;
var2 = temp;
}
public static void main(String [] args)
{
Point p1 = new Point(0,0);
Point p2 = new Point(0,0);
System.out.println("A: " + p1.x + " B: " +p1.y);
System.out.println("A: " + p2.x + " B: " +p2.y);
System.out.println(" ");
swap(p1,p2);
System.out.println("A: " + p1.x + " B:" + p1.y);
System.out.println("A: " + p2.x + " B: " +p2.y);
}
运行代码会产生:
A: 0 B: 0
A: 0 B: 0
A: 100 B: 100
A: 0 B: 0
我了解该函数如何更改 p1 的值,因为它是按值传递的。我不明白为什么 p1 和 p2 的交换失败了。