作者:手机用户2502901265_642 | 来源:互联网 | 2023-05-18 15:27
I have a Set
with a single element and I'm failing when using .contains with it and a new SelectDTO, as follows:
我有一个带有单个元素的Set
,当我使用.contains和一个新的SelectDTO时,我失败了,如下所示:
Set setDTOs = new HashSet
//processing where an element with is added.
SelectDTO selectDTO = new SelectDTO();
selectDTO.setName("ME101");
selectDTO.setId(102);
if (!setDTOs.contains(selectDTO)){
throw new Exception();
}
I have override SelectDTO's .hashCode()
, so that it's calculated as the sum of the parameters id and name. I have debugged and confirmed that the execution goes through .hashCode()
two times: the first when the element is added to the set and the second when calling .contains()
. Both elements' hashCode is -2024486876. But also, when debugging, I see that the table within the set has a single element, its "hash" being -1909995738.
我已经覆盖SelectDTO的.hashCode(),因此它被计算为参数id和name的总和。我已经调试并确认执行过两次.hashCode():第一次将元素添加到集合中,第二次调用.contains()时。两个元素的hashCode是-2024486876。但是,在调试时,我看到集合中的表有一个单独的元素,其“哈希”为-1909995738。
This is the code for my hashCode, although I don't think the problem's there:
这是我的hashCode的代码,虽然我不认为问题在那里:
@Override
public int hashCode() {
int result = 0;
result += this.getName() != null ? this.getName().hashCode() : 0;
result += this.getId() != null ? this.getId() : 0;
return result;
}
I guess that .contains()
is using this 'hash' value to compare, but I don't know why.
我想.contains()正在使用这个'hash'值进行比较,但我不知道为什么。
2 个解决方案