我正在尝试用 Java 开发数据结构,但遇到了一个我无法解决的问题。我有一个对象的引用,并且在复制它之后,我想只使用副本来更改原始引用。例如:
Point a = new Point(0,0);
Point b = a;
b = new Point(5,5);
我也希望“a”指向“new Point(5,5)”,而不仅仅是“b”。有没有办法做到这一点?
谢谢您的帮助。
Point a; // no need to instantiate
Point b = new Point(5,5);
a = b;
如果你制作 setter 方法,你可以这样做:
Point a = new Point(0,0);
Point b = a;
//b and a now reference the same point
b.setX(5);
b.setY(5);
//Now we have made changes to the point referenced by b
//Since a references the same point, these changes will
//also apply to a
你的例子的问题是你正在做new Point(x,y)
.
Point a = new Point(0,0);
Point b = a;
//At this point only one instance of Point exists.
//Both a and b reference the same Point.
//Any change you do to that point will be reflected through both a and b.
b = new Point(5,5);
//Now you have created a second instance of point.
//a and b reference the different points.
因此,总而言之,您必须了解修改现有点和创建新点以及只让一个参考引用新点之间的区别。
你不能在 Java 中做到这一点。您可以模拟它为 Point 创建一个包装器:
public class PointWrapper {
private Point point;
public PointWrapper(Point point) {
this.point = point;
}
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
}
PointWrapper a = new PointWrapper(new Point(0,0));
PointWrapper b = a;
b.setPoint(new Point(5,5));
当您创建 时new Point(5,5)
,会为 分配一个新引用b
,因此您将对a
和有不同的引用b
。
保持对同一实例的引用,以便对 的更改b
也“可见”的唯一方法a
是将新值 (5,5) 设置为原始对象(也从Alderath解释):
b.setX(5);
b.setY(5);