gpt4 book ai didi

java - 如何在无法访问私有(private)变量的情况下创建实例的副本

转载 作者:行者123 更新时间:2023-12-02 05:45:23 25 4
gpt4 key购买 nike

我遇到了一点问题。让我先向您展示代码:

public class Direction {
private CircularList xSpeed, zSpeed;
private int[] dirSquare = {-1, 0, 1, 0};

public Direction(int xSpeed, int zSpeed){
this.xSpeed = new CircularList(dirSquare, xSpeed);
this.zSpeed = new CircularList(dirSquare, zSpeed);
}
public Direction(Point dirs){
this(dirs.x, dirs.y);
}
public void shiftLeft(){
xSpeed.shiftLeft();
zSpeed.shiftRight();
}
public void shiftRight(){
xSpeed.shiftRight();
zSpeed.shiftLeft();
}
public int getXSpeed(){
return this.xSpeed.currentValue();
}
public int getZSpeed(){
return this.zSpeed.currentValue();
}
}

现在假设我有一个 Direction 实例:

Direction dir = new Direction(0, 0);

正如您在 Direction 的代码中看到的,提供给构造函数的参数直接传递给其他类。人们无法确定它们是否保持不变,因为可能调用了shiftRight()和shiftLeft方法,这会改变这些数字。

我的问题是,如何创建一个全新的 Direction 实例,它基本上是 dir 的复制(不是通过引用)?

我看到的唯一方法是在 CircularList 和 Direction 中创建公共(public)方法,返回创建实例副本所需的变量,但这个解决方案看起来真的很脏,因为这些数字在被修改后不应该被触及提供给构造函数,因此它们是私有(private)的。

编辑1:

CircularList 是一个 ArrayList 的循环版本的类。你可以看到我给它提供了一个名为 dirSquare 的数组,然后是一个数字。该数字是该数组中的索引。因此,如果我输入的数字是例如 3,它将是 dirSquare 中的最后一个元素,其值为 0。当我使用 shiftRight 和 shiftLeft 时,索引会递增/递减,如果我递增传递最后一个元素的大小数组的元素,它循环并从第 0 个元素开始。如果我在另一边传递 0,也会发生同样的事情。这就是为什么它被称为循环列表。我无法使用 getXSpeed/getZSpeed 因为它们返回数组的值。我需要索引,它严格来说是一个实现变量。

最佳答案

解决此问题的常见方法是创建复制构造函数。可以找到一个示例 here

另一个解决方案是实现 Cloneable 接口(interface),但大多数开发人员建议不要这样做,包括 Effective Java 中的 Joshua Bloch,调用 Java 的 clonedeeply broken”。

关于java - 如何在无法访问私有(private)变量的情况下创建实例的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24123247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com