java - Simple HashSet 包含误解

标签 java set hashset

我不明白为什么 HashSet 在下一个例子中返回 false。代码:

import java.util.*;

public class Name {
    private String first, last;

    public Name(String first, String last){
        this.first = first; 
        this.last = last;
    }

    public boolean equals(Name n){
        return n.first.equals(first) && n.last.equals(last);
    }

    public int hashCode(){
        return 31*first.hashCode()+last.hashCode();
    }

    public static void main(String[] args){
        Set<Name> s = new HashSet<Name>();
        Name n1 = new Name("Donald", "Duck");
        Name n2 = new Name("Donald", "Duck");
        s.add(n1);

        System.out.print("HashCodes equal: ");
        System.out.println( n1.hashCode() == n2.hashCode());
        System.out.print("Objects equal: ");
        System.out.println( n1.equals(n2) );

        System.out.print("HashSet contains n1: ");
        System.out.println(s.contains(n1));

        System.out.print("HashSet contains n2: ");
        System.out.println(s.contains(n2));
    }

}

结果:

HashCodes equal: true
Objects equal: true
HashSet contains n1: true
HashSet contains n2: false

摘自 HashSet包含方法说明:

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

问题:为什么两个对象都返回 false,即使它们都不为空并且在 hesh 和值方面都相等?

最佳答案

因为您没有覆盖从Object 类继承的equals 方法。

    @Override
    public boolean equals(Object o){
        Name n = (Name)o;
        return n.first.equals(first) && n.last.equals(last);
    }

输出(演示 here ):

HashCodes equal: true
Objects equal: true
HashSet contains n1: true
HashSet contains n2: true

关于java - Simple HashSet 包含误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20266649/

相关文章:

java - 外部库会使应用变慢吗?

java - Spring Controller 设置问题?

c++ - 为什么编译器在我的 set_intersection 上给我一个错误?

python - 使用 `set` 从列表创建一个集合与解压到大括号中

java - 集合 removeAll 忽略大小写?

.net - 克隆 HashSet<T> 的有效方法?

java - 使用 Flyway 应用程序与 Pax Exam 集成来测试 OSGi 应用程序

sas - 在 SAS 中,位于 set 语句后面的冒号意味着什么?

rust - 如何在 Rust 中的外部数据类型上实现 std::hash::Hash 特征?

java - 为什么 for 循环没有越界错误(Java)