有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

集合<>的java问题。包含和哈希代码

我有一个Set<SelectDTO>只有一个元素,使用时失败了。包含一个新的SelectDTO,如下所示:

Set<SelectDTO> setDTOs = new HashSet<SelectDTO>
//processing where an element with <name = "ME101", id = 102> is added.

SelectDTO selectDTO = new SelectDTO();
selectDTO.setName("ME101");
selectDTO.setId(102);
if (!setDTOs.contains(selectDTO)){
     throw new Exception();
}

我已经覆盖了SelectDTO的.hashCode(),因此它被计算为参数id和name的总和。我已经调试并确认执行过程经历了两次.hashCode():第一次是在将元素添加到集合中时,第二次是在调用.contains()时。这两个元素的哈希代码都是-2024486876。但是,在调试时,我看到集合中的表只有一个元素,它的“hash”是-1909995738

这是我的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;
}

我猜.contains()正在使用这个“散列”值进行比较,但我不知道为什么


共 (2) 个答案

  1. # 1 楼答案

    Set.contains() documentation开始:

    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)).

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

  2. # 2 楼答案

    似乎您忘记在集合中添加selectDTO元素:

    setDTOs.add(selectDTO);
    

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