我创建的equals()和hashcode()没有做任何事情

时间:2013-05-01 10:13:34

标签: java equals hashset

在我的程序中,我有一个名为Cell的类,定义如下:

public class Cell {
    private int x;
    private int y;

    public Cell (int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals (Object o) {
        boolean result = false;
        if (o instanceof Cell) {
            Cell other = (Cell) o;
            result = (this.x == other.x && this.y == other.y)
        }
        return result;
    }

    @Override        
    public int hashCode() {
        int result = x;
        result = 31 * result + y;
        return result;
    }
}

我有一个Grid类,就像这样(许多方法被删除,变量名简化):

public class Grid {
    private Set<Cell> cellArray;

    public Grid() {
        cellArray = new HashSet<Cell>();
    }

    public Set<Cell> getCellArray() {
        return cellArray;
    }

    public void addCellArray(Cell cell) {
        cellArray.add(cell)
    }
}

在我的主体代码中,我接受了一个网格对象,如下所示:

public class Controller {
    private Grid grid;
    public Controller (Grid grid) (
        this.grid = grid;

然后,我有一系列看起来像这样的循环:

private set<Cell> cellArray = grid.getCellArray();

boolean endLoop = false;
 do {
    x = randomGenerator.nextInt(10);
    y = randomGenerator.nextInt(10);

    for (int i = 0; i < length; i++) {
        if (cellArray.contains(new Cell(x, y+i))) {
            continue;
        }
    }
    for (int j = 0; j < length; j++) {
        cellArray.add(new Cell(x, y+i));
    }
    endLoop = true;
} while(!endLoop);

我知道这是一个非常混乱,有太多的实例化(如果有人有指针让它变得更干净,请随意指出它们) - 然而,主要的问题是第一个for循环的事实用于检查cellArray是否包含项目 - 它似乎没有这样做。

没有错误消息,没有空指针或类似的东西。我已经尝试过调试它并看到它比较两个具有相同x和y值的单元格,而没有继续执行continue语句来再次启动do while循环。

我假设这是因为即使它们具有相同的值,它们也是不同的“对象”,因此不会相等。

如果它们的值相同,我怎么能解决这个问题并使它们彼此等同?

1 个答案:

答案 0 :(得分:2)

你的continue语句继续内部for - 循环(这里没用)。您可能希望继续外循环:continue outerLoop;,标签outerLoop:放在do {前面。

正如the Java API所述,contains方法应该依赖于您的equals方法,因此对象相等应该按预期工作。