java-使用相同的变量创建两个不同的矩阵

9fkzdhlc  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(245)

我目前正在使用netbeans ide开发conway的生活游戏版本,我想将单元格存储在矩阵中。对于下一代单元的操作,我将返回一个新的单元矩阵,该矩阵由输入矩阵计算得出。
代码如下:

public static Cell[][] nextGen(Cell[][] CellList)
        { 
            Cell[][] Copy = CellList.clone();

            for (int i = 0; i<Copy.length; i++)
            {
                for(int n = 0; n<Copy[i].length; n++)
                {
                    if (Copy[i][n].isAlive())
                    {
                        if (Cell.count(Copy, i, n) <= 1 || Cell.count(Copy, i, n) >= 4 )
                        {
                            CellList[i][n].kill();
                        }
                    }else
                    {
                        if (Cell.count(Copy, i, n) == 3)
                        {
                            CellList[i][n].born();
                        }
                    }
                }
            }

            return CellList;
        }

该类称为“cell”,它有一个私有布尔属性“alive”,可以使用public方法将其设置为false kill() 或者对公共方法是正确的 born() . 除了计算特定细胞周围活细胞的方法和计算新一代细胞的方法外,其他方法都是非静态的。
它不起作用的问题是,如果我对输入矩阵“celllist”进行任何更改,同样的事情也会发生在该矩阵的副本中。
如何让副本具有相同的值,但仅在输入矩阵中进行更改?谢谢你的帮助!

db2dz4w8

db2dz4w81#

你所做的是浅拷贝,你需要的是深拷贝。试试这个

public class Cell {

boolean alive = false;

protected Cell clone() {
    return new Cell(this);
}

public Cell() {

}

public Cell(Cell cell) {
    this.alive = cell.alive;
}

boolean isAlive() {
    return alive;
}

void kill() {
    alive = false;
}

void born() {
    alive = true;
}

static int count(Cell[][] cell, int j, int k) {
    return 1;
}

public static void main(String[] args) {
    Cell[][] CellList = new Cell[2][3];
    CellList[0][1] = new Cell();
    nextGen(CellList);
}

public static Cell[][] nextGen(Cell[][] CellList) {

    Cell[][] Copy = deepArrayCopy(CellList);

    for (int i = 0; i < Copy.length; i++) {
        for (int n = 0; n < Copy[i].length; n++) {
            if (Copy[i][n].isAlive()) {
                if (Cell.count(Copy, i, n) <= 1 || Cell.count(Copy, i, n) >= 4) {
                    CellList[i][n].kill();
                }
            } else {
                if (Cell.count(Copy, i, n) == 3) {
                    CellList[i][n].born();
                }
            }
        }
    }

    return CellList;
}

public static Cell[][] deepArrayCopy(Cell[][] celllist) {
    Cell[][] copy = new Cell[celllist.length][celllist[0].length];
    for (int i = 0; i < celllist.length; i++) {
        for (int k = 0; k < celllist[i].length; k++) {
            if (celllist[i][k] != null)
                copy[i][k] = celllist[i][k].clone();
        }
    }
    return copy;
}

}

相关问题