【发布时间】:2014-11-26 22:50:50
【问题描述】:
我需要在我的点和段类上将我的复制构造函数设置为深度复制,但我不确定我是否做得对。任何人都可以帮忙吗?
public class Segment implements SegmentInterface {
// two Points that hold endpoints of the segment
private Point p1;
private Point p2;
// Default constructor that will set the endpoints to new
// Points with values (0,0) and (4,4)
public Segment() {
//this(0, 0, 4, 4);
this.p1 = new Point(0, 0);
this.p2 = new Point(4, 4);
}
// Parameterized constructor that accepts (int x1, int y1, int x2, int y2)
// and creates and sets the endpoints
public Segment(int x1, int y1, int x2, int y2) {
//this.p1 = new Point(x1, y1);
//this.p2 = new Point(x2, y2);
if(x1 != x2 && y1 != y2){
this.p1 = new Point(x1, y1);
this.p2 = new Point(x2, y2);
}
else{
throw new IllegalArgumentException("undefined");
}
}
// Parameterized constructor that accepts (Point p1, Point p2) and sets both
// the endpoints to a deep copy of the Points that are passed in.
public Segment(Point p1, Point p2) {
if(p1 != p2){
this.p1 = new Point(p1.getX(), p1.getY());
this.p2 = new Point(p2.getX(), p2.getY());
}
else{
throw new IllegalArgumentException("Points cannot have same values!");
}
}
// Copy constructor that accepts a Segment and initializes the data (of the
// new Segment being created) to be the same as the Segment that was
// received.
public Segment(Segment other) {
this.p1 = other.p1;
this.p2 = other.p2;
}
请注意这不是全部代码!
我的积分等级是:
public class Point implements PointInterface {
// hold the x-value and the y-value of the Point
private int x;
private int y;
public int getX() {
return x;
}
public int getY() {
return y;
}
// default constructor that will set the values to (0, 0)
public Point() {
this.x = 0;
this.y = 0;
}
// parameterized constructor that will receive 2 ints (first the x
// coordinate and then the y)
// and set the data variables to the values received.
public Point(int x, int y) {
this.x = x;
this.y = y;
}
// A copy constructor that will receive a Point and then initializes the
// data
// Deep Copy
public Point(Point other) {
this.x = other.getX();
this.y = other.getY();
}
【问题讨论】:
-
注意:如果你让你的
Point类不可变,就不需要深拷贝... -
Java 中没有复制构造函数。你可以自己写一些类似的东西,但它的作用完全取决于你。编译器不关心它们,也没有任何额外的“设置”。我完全同意@OliverCharlesworth。你不需要这样做。 17 年来,我从未在 Java 中编写过“复制构造函数”或使用
clone()。 -
将最后一个构造函数的代码更改为
public Segment(Segment other) { this(other.p1, other.p2); }。但我也推荐 Oliver 的建议。 -
sn-ps 用于可运行的 js,不适用于 java,请删除它们
-
谢谢大家!实际上,我正在按照教授给我们的说明进行操作,这就是我需要使用该代码的原因。谢谢汤姆,它成功了!