从对象集中删除值

时间:2019-11-27 00:58:03

标签: java

虽然标题不像我希望的那样具有描述性。我将在这里进一步详细解释该问题。如果有帮助,那么这个问题与一个简单的数独游戏有关。

假设我们有一个尺寸为 size 的2D数组,其中包含一些对象。 该对象将包含一些值和一组包含该对象的值可以继承的可能值。

假设网格已经填充,并且它通过了数独游戏的初始条件(例如,两行或两列都不能包含相同的值)。现在我们必须为每个对象设置可能的值。

这是我遇到问题的地方。我的方法如下:

  1. 遍历网格并从(row,col)获取对象值。
  2. 将此值存储在某些变量中。我们称之为 value
  3. 从具有相同列#的每个对象的集合和具有相同行#的每个对象的集合中删除值。

当我尝试打印所有对象的集合时,它将返回一个空集合。 尝试调试此代码时,我意识到由于某些原因,值将从所有对象中删除,而不仅仅是具有相同行和相同列的对象。

下面是代码。

public class Cell {
    public int value;
    public Set<Integer> possible;

    public Cell(int value) {
        this.value = value;
        this.possible = new HashSet<>();
    }
}

// In main class.

int size = 4;
Cell[][] grid = new Cell[size][size];

Set<Integer> possible = new HashSet<>();

possible.add(1);
possible.add(2);
possible.add(3);
possible.add(4);

String[] sample = {"1..2", "..4.", ".1..", "..3."};

for(int row = 0; row < size; row++){
   for(int col = 0; col < size; col++){
       grid[row][col] = new Cell(Character.getNumericValue(sample[row].charAt(col)));

       grid[row][col].possible = possible;
   }
}


// Loop to remove value from possible values of all object's with the same row and
// all the object's with the same column.

for(int row = 0; row < size; row++){
    for(int col = 0; col < size; col++){
        value = grid[row][col].value;

        // This loop starts at the specified row or column and removes value from 
        // all sets with the same row and all sets with the same column.
        for(int index = 0; index < size; index++){
            grid[row][index].possible.remove(value);
            grid[index][col].possible.remove(value);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

错误在于您尝试分配集合的代码:

Set<Integer> possible = new HashSet<>();

// ...

for(int row = 0; row < size; row++){
   for(int col = 0; col < size; col++){
       // ...
       grid[row][col].possible = possible;
   }
}

您已经创建了一个集合,并将其分配给每个单元格;因此每个Cell对象都拥有对同一集合的引用。当您从该集合中删除一个数字时,它就不再是该集合中的-对于每个单元格,因为现在没有其他集合了。网格后来似乎有16个空集的原因是因为它实际上只有16个对同一个空集的引用。您从其中删除了所有四个数字,尽管使用了不同的引用。

在您的Cell构造函数中,分配this.possible = new HashSet<>();。像这样写它,而不是覆盖对循环中设置的possible的引用:

grid[row][col].possible.addAll(possible);

然后,每个单元格仍然具有不同的设置,并且它们可以容纳不同的内容。