如何创建唯一对象,以便groovy set.add将其视为唯一对象?

如何创建唯一对象,以便groovy set.add将其视为唯一对象?,groovy,Groovy,在下面的代码中,我创建了两个相等的对象。但是,当添加到集合时,它会被添加两次。如何确保集合保持唯一性 class Cell implements Comparable<Cell>{ int x; int y; Cell(_x, _y){ x = _x; y = _y; } int compareTo(Cell cell){ if (x == cell.x && y == cel

在下面的代码中,我创建了两个相等的对象。但是,当添加到集合时,它会被添加两次。如何确保集合保持唯一性

class Cell implements Comparable<Cell>{
    int x;
    int y;

    Cell(_x, _y){
        x = _x;
        y = _y;
    }

    int compareTo(Cell cell){
        if (x == cell.x && y == cell.y)
            return 0;
        if (x <= cell.x)
            return -1;
        else 
            return 1;
    }
}

Cell cell = new Cell(1,0);
Cell sameCell = new Cell(1,0);
def setOfLiveCells = [] as Set

assert setOfLiveCells.add(cell) // cell is added
assert cell == sameCell // cell equals
assert ! setOfLiveCells.add(sameCell) //Shouldn't it return false? How to ensure set     adds only unique objects of Cell?
类单元格实现可比较{
int x;
int-y;
单元格(x,y){
x=x;
y=_y;
}
整数比较(单元格){
if(x==cell.x&&y==cell.y)
返回0;

如果(x您需要实现
hashCode
equals

使用Groovy,您可以使用:


谢谢Tim!!今天又学到了一些新东西(Canonical transformation):)顺便问一句,我应该使用@groovy.transform.EqualsAndHashCode还是(import groovy.transform.EqualsAndHashCode,@EqualsAndHashCode)描述的方法哦,顺便说一句,我尝试了Canonical,但它不适用于私有字段。我如何使它适用于私有字段?谢谢:)
@groovy.transform.EqualsAndHashCode
class Cell implements Comparable<Cell>{
    int x
    int y

    Cell(_x, _y){
        x = _x
        y = _y
    }

    int compareTo(Cell cell){
        x <=> cell.x ?: y <=> cell.y ?: 0
    }
}
@groovy.transform.Canonical
class Cell implements Comparable<Cell>{
    int x
    int y

    int compareTo(Cell cell){
        x <=> cell.x ?: y <=> cell.y ?: 0
    }
}