简体   繁体   English

包含所有元素的二维数组的深拷贝

[英]Deep copy of 2D array with all elements

I am making a basic game using a 2D array (4x4) in which the elements (of object type with ints 1 to 16) must be switched around to reach a particular goal state, this state must be compared with the current state, hence the need for copying. I am making a basic game using a 2D array (4x4) in which the elements (of object type with ints 1 to 16) must be switched around to reach a particular goal state, this state must be compared with the current state, hence the需要复制。

So far I have:到目前为止,我有:

public void cloneArray() throws CloneNotSupportedException
    {
        ClassName copy = (ClassName)super.clone();
        copy.tiles = (Tile[][]) tiles.clone();
    }

Does this appear to be right, or am I missing something out?这似乎是正确的,还是我错过了什么?

You'll need to go one step further and do like so:您需要进一步 go 并这样做:

    ClassName copy = (ClassName)super.clone();
    copy.tiles = (Tile[][]) tiles.clone();
    for(int i = 0; i < copy.tiles.length; i++) {
        copy.tiles[i] = (Tile[]) tiles[i].clone();
    }

The reason is that clone makes a shallow copy of the top-level array, which is holding references to other arrays.原因是 clone 对顶层数组做了一个浅拷贝,它持有对其他 arrays 的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM