如何使用Groovy Set来获得独特的元素?

时间:2010-04-29 19:15:58

标签: groovy

这一定很简单,我仍然无法理解我错在哪里:

class A {
    boolean equals(o) { true }
}
def s = [new A(), new A()] as Set
assert s.size() == 1 // Assertion failed: actually gives 2

为了获得唯一性,我应该覆盖哪种方法?

1 个答案:

答案 0 :(得分:7)

hashCode,就像使用Java一样

class A {
    boolean equals(o) { true }
    int hashCode() { 1 }
}
def s = [new A(), new A()] as Set
assert s.size() == 1