英文:
How to check whether two sets contain the same objects
问题
我有一个类 IntegerType
:
public class IntegerType implements DataType {
private int value;
public IntegerType(int value) {
this.value = value;
}
@Override
public NativeType nativeType() {
return NativeType.INTEGER;
}
@Override
public int size() {
return Integer.BYTES;
}
@Override
public Integer value() {
return this.value;
}
@Override
public boolean equals(Object o) {
boolean result = false;
if (o == null || o.getClass() != getClass()) {
result = false;
} else {
IntegerType integerType = (IntegerType) o;
if (this.value == integerType.value()) {
result = true;
}
}
return result;
}
}
而我实际上想要检查两个包含 IntegerType
实例的集合是否相同,基于这些实例是否具有相同的 .value
参数:
IntegerType int1 = new IntegerType(1);
IntegerType int2= new IntegerType(1);
Set<IntegerType> set1 = new HashSet<>();
set1.add(int1);
Set<IntegerType> set2 = new HashSet<>();
set2.add(int2);
System.out.println(set1.equals(set2));
然而,运行上述代码会输出 false
。根据我理解的情况,它应该输出 true
,因为 int1.equals(int2)
是 true
。我在这里漏掉了什么?
英文:
I have a class IntegerType
:
public class IntegerType implements DataType {
private int value;
public IntegerType(int value) {
this.value = value;
}
@Override
public NativeType nativeType() {
return NativeType.INTEGER;
}
@Override
public int size() {
return Integer.BYTES;
}
@Override
public Integer value() {
return this.value;
}
@Override
public boolean equals(Object o) {
boolean result = false;
if (o == null || o.getClass() != getClass()) {
result = false;
} else {
IntegerType integerType = (IntegerType) o;
if (this.value == integerType.value()) {
result = true;
}
}
return result;
}
}
And I essentially want to check whether two sets containing instances of IntegerType
are the same based on whether the instances have the same .value
parameter:
IntegerType int1 = new IntegerType(1);
IntegerType int2= new IntegerType(1);
Set<IntegerType> set1 = new HashSet<>();
set1.add(int1);
Set<IntegerType> set2 = new HashSet<>();
set2.add(int2);
System.out.println(set1.equals(set2));
However running the above code prints out false
. From what I understand it should print true
since int1.equals(int2)
is true
. What am I missing here?
答案1
得分: 2
就像名字所示,HashSet
要求你重写 hashCode
方法,它用来确定两个对象是否可能相等。以下是一种可能的实现:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + value;
return result;
}
英文:
As the name suggests, HashSet
requires you to override the hashCode
method, which it uses to determine whether or not two objects could possibly be equal. Here is a possible implementation:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + value;
return result;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论