java - HashSet 包含方法,奇怪的行为

标签 java

<分区>

这是我的代码:

public class testGui {



    public static void main(String[] arg){
        class TESTS{
            String t;

            public TESTS(String t){
                this.t = t;
            }

            @Override
            public boolean equals(Object x){
                System.out.println("My method is called...");
                if(x instanceof TESTS){
                    TESTS zzz = (TESTS) x;
                    return zzz.t.compareTo(t)==0;
                }
                else return false;
            }
        }
        HashSet<TESTS> allItems = new HashSet<TESTS>();
        allItems.add(new TESTS("a"));
        allItems.add(new TESTS("a"));
        System.out.println(allItems.contains(new TESTS("a")));
    }

}

我不明白为什么 hashset contains 方法没有像他们的规范中提到的那样调用我的 equals 方法:

More formally, adds the specified element, o, to this set if this set contains no element e such that (o==null ? e==null : o.equals(e))

我的代码返回 false 并且没有进入我的 equals 方法。

非常感谢您的回答!

最佳答案

当您覆盖 equals 时,您还必须覆盖 hashCode .否则,相等的对象将具有不同的哈希码并被视为不相等。

还强烈建议不要覆盖 only hashCode。但这不是必需的,因为不相等的对象可以具有相同的哈希码。

关于java - HashSet 包含方法,奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5505580/

相关文章:

Java Applet - 如何为 JButton 添加双缓冲

java - "org.json.JSONArray implements Serializable": What's the best option to achieve this?

java - 如何在hibernate中使用命名查询访问子表字段

java eclipse : failed to load nxt usb comm driver

java - 惯用的 Java : constraining data

java - Spring中泛型实例变量的依赖Bean注入(inject)

java - Eclipselink 和更新触发对数据库的多次访问

java - 从 Broadleaf 框架社区连接到 MySQL

java - 从 for 循环中取出可迭代变量

java - 为什么需要工厂模式,因为我可以使用多态性完成任务?