gpt4 book ai didi

java - 比较器不适用于 TreeSet 中的对象类型

转载 作者:行者123 更新时间:2023-12-01 16:50:29 26 4
gpt4 key购买 nike

我试图借助带有自定义ComparatorTreeSet 来消除列表中的重复对象。对于此代码:

class ASDF {
int i
Pass ref
new(Pass p, int i) {
this.ref = p
this.i=i
}
public static def void main(String[] args) {
val list = new TreeSet(
new Comparator<ASDF> {
override compare(ASDF obj1, ASDF obj2) {
if (obj1.ref == obj2.ref && obj1.i == obj2.i) {
return 0
}
return 1
}
}
)
val a1 = new ASDF(new Pass("p1"), 1)
val a2 = new ASDF(new Pass("p2"), 2)
val a3 = new ASDF(new Pass("p3"), 3)
val a4 = new ASDF(new Pass("p4"), 4)
list.addAll(
a1, a2, a3, a4
,
a1, a2, a3, a4
,
a1, a2, a3, a4
,
a1, a2, a3, a4
)
println(list.map['''«ref.s»->«i»'''])
}
}

class Pass {
@Accessors
String s
new (String s) {
this.s=s
}
}

Actual output on console: [p1->1, p2->2, p3->3, p4->4, p1->1, p3->3]

Expected output on console: [p1->1, p2->2, p3->3, p4->4]

为什么我在集合中再次出现 p1p3?我在 Comparator 中哪里出错了?

注意:这只是一个示例代码片段。在我的“真实”代码中,我无法覆盖 equalshashcode

最佳答案

如果您违反 Comparator 的契约(Contract),不要指望TreeSet行为正确。

也就是说,您未能使比较器对称:

Pass p1 = new Pass("p1");
Pass p2 = new Pass("p2");
compare(p1, p2); // returns 1
compare(p2, p1); // also returns 1 - not good
<小时/>

如果您不关心(或者甚至无法定义)总排序,那么使用正确定义的 hashCode() 会做得更好。和equals()和一个 HashSet .

如果您无法覆盖这些(如您所写),请创建 Key将保存相关属性的类,定义 KeyhashCode()equals()并使用 HashMap<Key, Pass> 。或者,Key可能只是一个包含对 Pass 的引用的包装器并导出它的哈希码并等于 Pass 中的信息' 字段。

关于java - 比较器不适用于 TreeSet 中的对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41060296/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com