用Set实现等于 [英] Implement equals with Set

查看:36
本文介绍了用Set实现等于的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上了这个课:

 私有静态类ClassA {int id;字符串名称;公共ClassA(int id,字符串名称){this.id = id;this.name =名称;}@Overridepublic boolean equals(Object o){return((ClassA)o).name.equals(this.name);} 

}

如果我要重写ClassA中的equals方法以仅比较名称,为什么这个主体打印2个元素?

  public static void main(String [] args){ClassA myObject =新的ClassA(1,测试1 2 3");ClassA myObject2 =新的ClassA(2,"testing 1 2 3");设置< ClassA>set = new HashSet< ClassA>();set.add(myObject);set.add(myObject2);System.out.println(set.size());//将显示2,但我想成为1!} 

如果我查看Set Java 文档:

不包含重复元素的集合.更正式地说,集合不包含元素对e1和e2,使得e1.equals(e2)最多包含一个空元素.顾名思义,该接口对数学集抽象进行了建模.

显然,我只需要重写等于,但是我听说我也必须重写哈希码,但是为什么呢?

解决方案

它们具有不同的哈希值,因为您没有覆盖hashCode.这意味着它们被放在HashSet中的两个不同的存储桶中,因此它们从来没有与等值进行比较.

我会添加

  public int hashCode(){返回name.hashCode();} 

hashCode中不使用通知ID,因为在等号中也不使用通知ID.

(PS,我也想指出讽刺的是,没有在等号中使用一个id.这很有趣.通常是相反的方式:该号是等号中唯一的东西!)

I have this class:

private static class ClassA{
int id;
String name;

public ClassA(int id, String name){
    this.id= id;
    this.name = name;
}

@Override
public boolean equals(Object o) {
    return ((ClassA)o).name.equals(this.name);
}   

}

Why this main is printing 2 elements if I am overwriting the method equals in ClassA to compare only the name?

public static void main(String[] args){
    ClassA myObject = new ClassA(1, "testing 1 2 3");
    ClassA myObject2 = new ClassA(2, "testing 1 2 3");    

    Set<ClassA> set = new HashSet<ClassA>();
    set.add(myObject);
    set.add(myObject2);   
    System.out.println(set.size()); //will print 2, but I want to be 1!
}

If I look into the Set Java documentation:

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

So apparently I only have to override equals, however I heard that I have also to override the hashcode, but why?

解决方案

They have different hashes because you didn't override hashCode. This means they were put in two different buckets in the HashSet, so they never got compared with equals in the first place.

I would add

public int hashCode() {
    return name.hashCode();
}

Notice id isn't used in the hashCode because it isn't used in equals either.

(P.S. I'd also like to point out the irony of having an id that isn't used in equals. That's just funny. Usually it's the other way around: the id is the only thing in equals!)

这篇关于用Set实现等于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆