如何包含Set集合的方法

use*_*224 2 java collections

嗨,我是java的新手,因为我知道set collection不会重复,当contains已经存在于collection中时,它的contains方法应该返回true.我试图在程序下运行,但我得到了意想不到的结果.

public class UserDefinedName {
    private final String first, last;

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

    public boolean equals(Object o) {
        if (!(o instanceof UserDefinedName))
            return false;
        UserDefinedName n = (UserDefinedName) o;
        return n.first.equals(first) && n.last.equals(last);
    }

    public static void main(String[] args) {
        Set<UserDefinedName> s = new HashSet<UserDefinedName>();
        s.add(new UserDefinedName("Carballo", "Videl"));
        System.out.println(s.contains(new UserDefinedName("Carballo", "Videl")));
    }
}
Run Code Online (Sandbox Code Playgroud)

我期待输出为true但程序打印为false.我做错了什么?

Vip*_*pul 8

形成java doc

如果两个对象根据equals(Object)方法相等,则对两个对象中的每一个调用hashCode方法必须生成相同的整数结果.

如果hashCode()方法没有覆盖,则使用Object的hashCode()方法,这是默认实现.

在你的情况下,你有覆盖equals方法,但你使用hashCode()的默认实现,因为你没有覆盖UserDefinedName类中的hashCode()方法.

UserDefinedName类重写equals方法,hashCode契约要求相等的对象具有相同的哈希码.要完成此合约,只要覆盖equals,就必须覆盖hashCode

添加以下代码,它将工作.

public int hashCode() {
return 37 * first.hashCode() + last.hashCode(); 
}
Run Code Online (Sandbox Code Playgroud)