gpt4 book ai didi

Java,这是深拷贝吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:01:32 26 4
gpt4 key购买 nike

我似乎无法通过阅读任何类似的问题得到明确准确的答案,我正在尝试使用复制构造函数在 Java 中深度克隆一个对象,这是一个深度复制:

public class Tile{
Image sprite = null;
int x = 0;
int y = 0;
public Tile(Image setImage, int sX, int sY){
this.sprite = setImage;
this.x = sX;
this.y = sY;
}
public Tile(Tile copyTile){
this.sprite = copyTile.sprite;
this.x = copyTile.x;
this.y = copyTile.y;
}
public void setNewLocation(int sX, int sY){
this.x = sX;
this.y = sY;
}
}

然后当我创建我的瓦片 map 时,我可以做这样的事情

List<Tile> tileList = new List<Tile>();
Tile masterGrassTile = new Tile(grassImage, 0,0);
tileList.set(0,new Tile(masterGrassTile));
tileList.set(1,new Tile(masterGrassTile));
tileList.get(0).setNewLocation(0,32);
tileList.get(1).setNewLocation(0,64);

如果我要在各自的位置渲染两个图 block ,那行得通吗?或者是分配 tileList.get(1).setNewLocation(0,64);像引用一样起作用,并且它们都与上次赋值具有相同的位置。

最佳答案

is this a deep copy ?

不,这不是因为 this.sprite = copyTile.sprite; Tile 的两个对象都引用 Image 的同一个对象。

If i were to render both tiles at their respective locations would that work? or was the assignment tileList.get(1).setNewLocation(0,64); effecting like a reference and all of them have the same location as the last assignment.

不,x 和 y 的值在 Tiles 的两个对象中是独立的,代码应该可以工作,两个对象将具有不同的 x 和 y 值。

关于Java,这是深拷贝吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15610909/

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