java - 复制数组,当构造函数的输入发生变化时允许它保持不变

标签 java encapsulation

我的点类是不可变的。当我最初向构造函数提供输入时,应该将其复制到 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/

相关文章:

java - 应用程序关闭时 Android 警报管理器挂起 Intent

c++ - 我可以在不使用 friend 的情况下从类外访问私有(private)成员吗?

c++ - 多个类,相同的公共(public)接口(interface)

java - NullPointerException - 无法看到我的问题

java - hibernate java.lang.NoClassDefFoundError : org/hibernate/util/DTDEntityResolver

java - 使用kafkastreams根据记录内容上的内容写入kafka Topic

java - Parquet 文件可选字段不存在

python - 什么时候重构?

wcf - 将 WCF 代理封装在静态类中

C++:传递给非好友的友元函数