热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Set<>。contains和hashCode的问题-ProblemswithSet<>.containsandhashCode

IhaveaSet<SelectDTO>withasingleelementandImfailingwhenusing.containswithitand

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 个解决方案

#1


4  

From the Set.contains() documentation:

从Set.contains()文档:

Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).

如果此set包含指定的元素,则返回true。更正式地,当且仅当此集合包含元素e时才返回true(o == null?e == null:o.equals(e))。

In other words, you do not only need to implement hashCode(), but also equals().

换句话说,您不仅需要实现hashCode(),还需要equals()。

#2


0  

It seems you forgot to add the selectDTO element in Set:

您似乎忘了在Set中添加selectDTO元素:

setDTOs.add(selectDTO);

Assuming you have added the element somewhere in your code, then you need to override the equals method and not hashCode. As contains() method uses equals() method to determine whether an element exist or not in the set. Interestingly, i believe this is how Set makes sure it does not push a duplicate element in the Set.

假设您已在代码中的某处添加了元素,那么您需要覆盖equals方法而不是hashCode。由于contains()方法使用equals()方法来确定集合中是否存在元素。有趣的是,我相信这就是Set确保它不会在Set中推送重复元素的方式。


推荐阅读
author-avatar
手机用户2502901265_642
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有