简体   繁体   English

为什么必须将Java中的equals()传递给Object作为参数?

[英]Why does equals() in Java must be passed Object as a parameter?

When we override the equals() method in Java, I know that Object needs to be a parameter, but I wonder - why Object ?. 当我们在Java中重写equals()方法时,我知道Object必须是一个参数,但我想知道-为什么选择Object ?。

Second, let us say we override hashcode() and implement equals() , but set the parameter in equals() to MyClass instead of Object ( MyClass being the class whose equals() method we override). 其次,让我们说我们覆盖hashcode()和实施equals() ,而是设置在参数equals()MyClass而不是ObjectMyClass是其类equals()方法中,我们重写)。 Will we still get the expected behavior if we use HashMap ? 如果使用HashMap我们是否还会得到预期的行为?

Update: Yes, it will be overloading instead of overriding. 更新:是的,它将过载而不是覆盖。 But what will happen if we use HashMap with overloaded equals() ? 但是,如果我们将HashMap与重载的equals()一起使用会发生什么? Also, I don't find the answer in related posts. 另外,我在相关帖子中找不到答案。 Or is it something obvious that I am missing? 还是我想念的东西很明显?

If you write an equals() method whose parameter is not Object, you are overloading the method, not overriding it. 如果编写参数不是Object的equals()方法,则将重载该方法,而不是对其进行覆盖。

Now, as for HashMap - HashMap calls equals to compare keys. 现在,对于HashMap - HashMap调用等于以比较键。 The type of the compared keys is Object . 比较的键的类型为Object Therefore, if you define an equals() method with a parameter whose not Object , this method will be ignored by HashMap . 因此,如果使用参数不是Objectequals()方法定义该方法,则HashMap将忽略该方法。

I tried the following code : 我尝试了以下代码:

public class SomeClass
{
    int privateMember;

    // note it's important to override hashCode, since if the hashCode of two
    // keys is not the same, equals() won't be called at all
    public int hashCode ()
    {
        return privateMember;
    }

    public boolean equals (Object other)
    {
        if (other instanceof SomeClass) {
            return this.privateMember==((SomeClass)other).privateMember;
        }
        else { 
            return false;
        }
    }

    public static void main(String[] args)
    {
        HashMap<SomeClass,String> map = new HashMap<SomeClass,String>();
        SomeClass s1 = new SomeClass ();
        SomeClass s2 = new SomeClass ();
        s1.priv=4;
        s2.priv=4;
        map.put (s1, "something");
        if (map.containsKey (s2)) {
            System.out.println ("found!");
        } else {
            System.out.println ("not found!");
        }
    }
}

This code outputs "found!". 此代码输出“找到!”。

Now, if you run the exact same code, but replace the equals method with : 现在,如果您运行完全相同的代码,但是将equals方法替换为:

    public boolean equals (SomeClass other)
    {
        if (other instanceof SomeClass) {
            return this.privateMember==((SomeClass)other).privateMember;
        }
        else { 
            return false;
        }
    }

The output will be "not found!", which means our equals method was ignored. 输出将为“未找到!”,这意味着我们的equals方法将被忽略。

The collections use the equals and hashcode methods from the Object base class. 集合使用Object基类中的equals和hashcode方法。 Therefore you must override them in order for your custom class to provide an implementation. 因此,您必须重写它们,以便您的自定义类提供实现。 You can overload equals if you wish, and that would work for situations where some code knows that it's dealing with an instance of MyClass . 您可以根据需要重载equals,这在某些代码知道它正在处理MyClass实例的情况下适用。 However, this would be misleading. 但是,这将产生误导。

All the collections classes are designed to work with instances of Object and Object provides a general purpose equals method. 所有集合类均设计为可与Object实例一起使用,并且Object提供了通用的equals方法。

You shouldn't really need to write an equals method directly. 您实际上不需要直接编写equals方法。 You can either generate one using your IDE, or use EqualsBuilder from Apache Commons ( https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/builder/EqualsBuilder.html ) to help put it all together. 您可以使用自己的IDE生成一个,也可以使用Apache Commons( https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/builder/EqualsBuilder的 EqualsBuilder 。 html ),以帮助将它们放在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么List.indexOf使用equals方法传入Object? - Why does List.indexOf use equals method of passed in Object? 在Java中覆盖equals时,为什么使用Object以外的参数不起作用? - When overriding equals in Java, why does it not work to use a parameter other than Object? java 为什么 equals 方法输入参数应该是 Object - java why should equals method input parameter be Object 为什么(不是如何)Object必须符合equals()的javadoc? - Why (not how) must an Object conform to the javadoc of equals()? 为什么 Java 不允许在枚举中覆盖 equals(Object)? - Why Java does not allow overriding equals(Object) in an Enum? 为什么Java HashSet.equals()不检查对象是否相等? - Why does not Java HashSet.equals() check for object equality? 在 Java 中,为什么 equals() 和 hashCode() 必须一致? - In Java, why must equals() and hashCode() be consistent? 为什么Java的Area#equals方法不会覆盖Object#equals? - Why does Java's Area#equals method not override Object#equals? 为什么java传递lambda表达式时将type-argument设置为object,其类型为parameter-和return-type? - Why does a java set the type-argument to object when a lambda expression is passed that has the type as parameter- and return-type? 如果存在hashCode(),为什么Java需要equals()? - Why does Java need equals() if there is hashCode()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM