我正在使用一个具有x和y分量的Point对象,Point(double x,double y)。我想编写一个函数来更改x和y组件的值而不需要 新点p = ... 例如,这是我当前的版本:
public class Point{
private double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Point movePoint(double dx, double dy) {
return new Point(this.x + dx, this.y + dy);
}
}
是否可以在不制作新Point的情况下执行movePoint()这样的操作? 提前谢谢。
答案 0 :(得分:3)
当然可以。只需更改代码即可返回对this
的引用:
public Point movePoint(double dx, double dy) {
this.x += dx;
this.y += dy;
return this;
}
另请注意,Java有一个内置类,用于在java.awt.geom.Point2D.Double
类中存储双精度点。
答案 1 :(得分:1)
当然,试试这个:
public class Point{
private double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Point movePoint(double dx, double dy) {
this.x += dx;
this.y += dy;
return this;
}
}