gpt4 book ai didi

java - 复制一个对象数组,然后在不影响副本的情况下修改原始对象

转载 作者:行者123 更新时间:2023-11-30 08:59:39 25 4
gpt4 key购买 nike

所以我一直在为这个看似微不足道的问题苦思冥想。我不一定知道要搜索什么。我四处寻找解决方案。我需要复制二维数组。该数组由对象(我创建的一个称为 Cell 的类)组成,但是一旦我制作了一个副本,我就将该副本存储到一个 HashMap 中(以供稍后引用),然后继续修改原始数组。问题是对原件的修改也会影响散列映射中的副本。基本上在一天结束时,我的散列映射将由同一网格的多个版本组成。我已经尝试过 array.clone()、System.arraycopy(...)、Arrays.copyof(),传统的 for 循环复制方案....最后我意识到我需要所谓的深度复制,在那里你复制每个对象的每个数据字段到一个新对象到数组副本中......是的,那也没有用。看一看:

static Cell[][] gridCopy;
...
Cell[][] grid = getGrid(file); //get grid from a file (this is Sudoku if you must know)
...
static boolean SolveSudoku(Cell grid[][])
{
// If there is no unassigned location, we are done
if (unassigned == null)
return true; // success!

int row = unassigned.row;
int col = unassigned.col;
ArrayList<Integer> domain = unassigned.domain;

// consider digits 1 to 9
for (int num = 0; num < domain.size(); num++)
{
//if looks promising
if (isSafe(grid, row, col, domain.get(num)))
{
//gridCopy = new Cell[N][N];
instance++;
// make tentative assignment
grid[row][col].value = domain.get(num);

//here is my attempt at a deep copy
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
gridCopy[i][j] = new Cell(grid[i][j].row, grid[i][j].col, grid[i][j].value, grid[i][j].domain);
states.put(instance, gridCopy); //save the current state in a map for reference if we backtrack

//as soon as I change things here in the original, the copy in the 'states' map also changes
updateSpecifiedDomains(grid, row, col, domain.get(num), true);

printGrid(grid, "Instance" + String.valueOf(instance));

// return, if success, yay!
if (SolveSudoku(grid, choice))
return true;

// failure, un-assign & try again
//int temp = grid[row][col].value;
grid = states.get(instance); //retain previous state
grid[row][col].value = UNASSIGNED;

/*updateSpecifiedDomains(grid, row, col, temp, false);
while (domain.contains(temp))
grid[row][col].domain.remove((Integer)temp);*/

//domain.remove((Integer)num);
}
}
count++;
instance--;
return false; // this triggers backtracking
}

最佳答案

您正在创建对象的浅拷贝。 Array.clone() 仅适用于基本类型。您应该在要复制的对象的类中创建一个方法,该方法创建并返回具有相同属性值的类的新实例。然后你可以遍历你的数组获取每个对象的副本并将它们添加到一个新数组然后将新数组存储到你的 HashMap 中。

例子:

public class MyClass()
{
private String temp;

public MyClass(String temp)
{
this.temp = temp;
}

public MyClass copy()
{
MyClass copy = new MyClass(this.temp);
//set attributes in constructor or using setters so they are the same as this object
return copy;
}
}

关于java - 复制一个对象数组,然后在不影响副本的情况下修改原始对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27136139/

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