gpt4 book ai didi

java - 如何使 java HashSet/HashMap 与任何对象一起工作?

转载 作者:行者123 更新时间:2023-12-01 17:35:11 25 4
gpt4 key购买 nike

是否可以使 HashSet 与任何对象一起工作?我试图让对象实现可以比较,但没有帮助

import java.util.HashSet;
public class TestHashSet {
public static void main(String[] args) {
class Triple {
int a, b, c;

Triple(int aa, int bb, int cc) {
a = aa;
b = bb;
c = cc;
}
}
HashSet<Triple> H = new HashSet<Triple>();
H.add(new Triple(1, 2, 3));
System.out.println(H.contains(new Triple(1, 2, 3)));//Output is false
}
}

最佳答案

您需要实现equals(Object)hashCode()

确保对象相等时哈希码也相等

在您的示例中:

class Triple {
int a, b, c;

Triple(int aa, int bb, int cc) {
a = aa;
b = bb;
c = cc;
}

public boolean equals(Object arg){
if(this==arg)return true;
if(arg==null)return false;
if(arg instanceof Triple){
Triple other = (Triple)arg;
return this.a==other.a && this.b==other.b && this.c==other.c;
}
return false;
}

public int hashCode(){
int res=5;
res = res*17 + a;
res = res*17 + b;
res = res*17 + c;
//any other combination is valid as long as it includes only constants, a, b and c

return res;
}

}

关于java - 如何使 java HashSet/HashMap 与任何对象一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7214732/

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