HashSet包含方法,奇怪的行为 [英] HashSet contains method, strange behavior

查看:74
本文介绍了HashSet包含方法,奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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方法:

I do not get why the hashset contains method is not calling my equals method as mentionned in their specifications :


更正式地说,添加指定的
元素o,如果这个集合
不包含元素e,那么
(o == null?e == null:o.equals(e))

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方法。

My code is returning false and not going into my equals method.

非常感谢您的回答!

推荐答案

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

When you override equals, you must also override hashCode. Otherwise, equal objects will have different hash codes and be considered unequal.

强烈建议不要仅覆盖 的hashCode 。但这并不重要,因为不等对象可以具有相同的哈希码。

It is also strongly recommended not to override only hashCode. But this is not essential, as unequal objects can have the same hash code.

这篇关于HashSet包含方法,奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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