java Java中的equals()方法是如何工作的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15542656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:00:02  来源:igfitidea点击:

How does equals() method work in Java

javaoverridingequals

提问by Hymanyesind

The equalsmethod compares whether two object values are equal or not. My question is how it compares the two objects? How can it tell the two objects are equal or not? I want to know based on what it compares the two objects. I am not including the hashCodemethod.

equals方法比较两个对象值是否相等。我的问题是它如何比较这两个对象?它如何判断两个对象是否相等?我想知道基于它比较两个对象的内容。我不包括hashCode方法。

回答by Denys Séguret

The default implementation, the one of the class java.lang.Object, simply tests the references are to the same object :

默认实现,类之一java.lang.Object,简单地测试对同一对象的引用:

150    public boolean equals(Object obj) {
151        return (this == obj);
152    }

The reference equality operator is described like this in the Java Specification:

Java 规范中对引用相等运算符的描述如下:

At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false.

在运行时,如果操作数值都为 null 或都指向同一个对象或数组,则 == 的结果为真;否则,结果为假。

This default behavior isn't usually semantically satisfying. For example you can't test equality of big Integer instances using ==:

这种默认行为通常在语义上并不令人满意。例如,您不能使用以下方法测试大 Integer 实例的相等性==

Integer a = new Integer(1000);
Integer b = new Integer(1000);
System.out.println(a==b); // prints false

That's why the method is overridden :

这就是该方法被覆盖的原因:

722     public boolean equals(Object obj) {
723         if (obj instanceof Integer) {
724             return value == ((Integer)obj).intValue();
725         }
726         return false;
727     }

which enables this :

这可以实现:

System.out.println(a.equals(b)); // prints true

Classes overriding the default behavior should test for semantic equality, based on the equality of identifying fields (usually all of them).

覆盖默认行为的类应该基于标识字段(通常是所有字段)的相等性来测试语义相等性。

As you seem to know, you should override the hashCodemethod accordingly.

正如您似乎知道的那样,您应该相应地覆盖该hashCode方法。

回答by AmitG

Consider following example,

考虑下面的例子,

public class Employee {
    String name;
    String passportNumber;
    String socialSecurityNumber;
    public static void main(String[] args) {
        Employee e1 = new Employee();
        Employee e2 = new Employee();
        boolean isEqual = e1.equals(e2);  // 1
        System.out.println(isEqual);
    }
}

In the code at comment //1 it calls inherited equalsmethod from Object class which is simply comparing references of e1and e2. So it will always give falsefor each object created by using newkeyword.

在注释 //1 的代码中,它调用了equalsObject 类的继承方法,该方法只是比较e1和 的引用e2。所以它总是会false为使用new关键字创建的每个对象提供。

Following is the method excerpt from Object

以下是Object的方法摘录

public boolean equals(Object obj) {
    return (this == obj);
}

For comparing equality check JLS has given equalsmethod to override in our class. It is not final method. JLS doesn't know on what basis programmar wants to make two objects equal. So they gave non-final method to override.
hashcodedoes not play role to check object's equality. hashcodechecks/finds the Bucket where object is available. we use hashcodein hashing technique which is used by some classes like HashMap..

为了比较相等性检查,JLS 提供了equals在我们的类中重写的方法。这不是最终方法。JLS 不知道 programmar 想让两个对象相等的依据是什么。所以他们给出了非最终方法来覆盖。
hashcode不会起到检查对象是否相等的作用。hashcode检查/查找对象可用的 Bucket。我们使用hashcode散列技术,它被一些类使用,比如 HashMap..

If two object's hashcode are equals that doesn't means two objects are equal.
For two objects, if equalsmethod returns true then hashcode must be same.

如果两个对象的哈希码相等,并不意味着两个对象相等。
对于两个对象,如果equals方法返回 true 则哈希码必须相同。

You will have to override equalsmethod to decide on which basis you want object e1and e2in above code is equal. Is it on the basis of passportNumberor socialSecurityNumberor the combination of passportNumber+socialSecurityNumber?

您将不得不重写equals方法来决定您想要对象的基础,e1并且e2在上面的代码中是相等的。是的基础上,passportNumbersocialSecurityNumber或组合passportNumber+socialSecurityNumber

I want to know based on what it compares the two objects.

Answer is, by default with the help of inherited Objectclass's equalsmethod it compares two object's reference equality by using == symbol. Code is given above.

答案是,默认情况下,在继承Objectequals方法的帮助下,它使用 == 符号比较两个对象的引用相等性。上面给出了代码。

回答by Ankit

logically, equals does not compare objects (however you can do anything with it), it compares values. for object comparison there is '==' operator

从逻辑上讲,equals 不比较对象(但是你可以用它做任何事情),它比较值。对于对象比较,有“==”运算符