在下面的代码中,我创建了两个相等的对象。但是,添加到set时,会添加两次。如何确保该集合保持唯一?
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?
谢谢!
此致 约翰
答案 0 :(得分:3)
您需要实施hashCode
和equals
使用Groovy,您可以使用annotation:
执行此操作@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
}
}
您还可以使用Canonical
transformation,取消自定义构造函数(并自动获得toString
):
@groovy.transform.Canonical
class Cell implements Comparable<Cell>{
int x
int y
int compareTo(Cell cell){
x <=> cell.x ?: y <=> cell.y ?: 0
}
}