我的点类是不可变的。当我最初向构造函数提供输入时,应该将其复制到 cloneList 对象中。如果通过构造函数更改了数组中的几个索引,这将允许它保持以前的方式。我已经尝试了几乎所有可能的组合,但仍然遇到麻烦。我希望克隆列表是原始 Point[] 点数组的副本,因此如果点数组发生更改,则克隆列表不会更改。
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Polygon {
private double xSum = 0;
private double ySum = 0;
private Point[] points;
private Point[] cloneList;
private Point a;
public Polygon(Point[] points) {
this.points = points;
cloneList = new Point[points.length];
for (int i = 0; i < cloneList.length; i++) {
cloneList[i] = points[i];
}
for (int i = 0; i < cloneList.length; i++)
System.out.println(cloneList[i]);
for (int i = 0; i < points.length; i++){
cloneList[i] = points[i];
// System.out.print(cloneList[i].getX());
// System.out.print(cloneList[i].getY());
// System.out.println();
}
public Point getVertexAverage() {
double xSum = 0;
double ySum = 0;
for (int index = 0; index < cloneList.length; index++) {
xSum = xSum + cloneList[index].getX();
ySum = ySum + cloneList[index].getY();
}
return new Point(xSum / getNumSides(), ySum / getNumSides());
}
public int getNumberSides() {
return cloneList.length;
}
}
最佳答案
根据我对您帖子的评论,解决您问题的一个选项是将新 Point
实例添加到您的cloneList
数组中:
public PolygonImpl(Point[] points) {
//some code here...
for (int i = 0; i < cloneList.length; i++) {
//create the new Point instance (the clone) here
//this code is just an example since you haven't provided the Point constructor
cloneList[i] = new Point(points[i].getX(), points[i].getY());
}
//some more code here...
}
但是这个选项有点笨拙,因为当向 Polygon
接口(interface)(或 PolygonImpl
类)的客户端提供 cloneList
属性时它会修改数组(因为数组是可变的)并且原始的cloneList也会被修改。知道这一点,最好不要使用 cloneList
作为属性,而是在方法上创建此列表:
public Point[] getPoints() {
Point[] cloneList = new PointList[X]; //where X is some size you know
for (int i = 0; i < cloneList.length; i++) {
//create the new Point instance (the clone) here
//this code is just an example since you haven't provided the Point constructor
cloneList[i] = new Point(points[i].getX(), points[i].getY());
}
return cloneList;
}
我提倡此选项,因为您的 Point
类中似乎几乎没有数据。对于现实世界的应用程序,您的类将更加复杂(例如有一个内部对象列表,其中包含更多对象实例,形成一个复杂的树),您不应该创建这样的东西(因为它将是一个 < strong>人间 hell ),而是使用复制/克隆方法。为此,您可以使用此处提供的一些技术:Java: recommended solution for deep cloning/copying an instance
关于java - 复制数组,当构造函数的输入发生变化时允许它保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16160827/