java 为什么在使用 equals() 方法时具有相同数据的两个对象不相等

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17064661/
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-11-01 00:52:21  来源:igfitidea点击:

Why are two objects with same data not equal while using equals() method

javastringequals

提问by Sandeep Kumar Aitha

public class Account {

    String account;
    double balance;

    Account(String account, double balance) {
        this.account = account;
        this.balance = balance;
    }
}

public class AccountTest {

    public static void main(String[] args) {
        Account a1 = new Account("Sandy", 1000);
        Account a2 = new Account("Sandy", 1000);
        System.out.println(a1.equals(a2));
    }
}

When i execute it showing "false" but objects contains same data in variables.why?explain.

当我执行它时显示“false”但对象在变量中包含相同的数据。为什么?解释一下。

回答by Sumit Singh

Because by default object checks equality based on equals(Object obj).

因为默认情况下 object 根据equals(Object obj)检查相等性。

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Object 类的 equals 方法实现了对象上最有区别的可能等价关系;也就是说,对于任何非空引用值 x 和 y,当且仅当 x 和 y 引用同一个对象(x == y 的值为 true)时,此方法才返回 true。

If you want to check equality with equals()method in your class equal you have to override equals() method of Objectclass.
how-to-override-equals-method-in-java, Like following:

如果要检查equals()类中的方法是否相等,则必须覆盖类的 equals() 方法Object
how-to-override-equals-method-in-java,如下所示:

@Override
public boolean equals(Object obj) {
   // your implementation 
}

And you should always override hashCode() whenever overriding equalsmethod of Objectclass.

并且您应该始终覆盖 hashCode() 每当覆盖Object类的equals方法时。

#Effective Java, by Joshua Bloch

#Effective Java,作者 Joshua Bloch

You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.

您必须在每个覆盖 equals() 的类中覆盖 hashCode()。不这样做将导致违反 Object.hashCode() 的一般契约,这将阻止您的类与所有基于哈希的集合(包括 HashMap、HashSet 和 Hashtable)一起正常运行。

回答by Suresh Atta

You need to override equals() method, and use it whenever you want to compare their values.

您需要覆盖 equals() 方法,并在想要比较它们的值时使用它。

@Override
public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final Account other = (Account) obj;
    if ((this.account== null) ? (other.account!= null) : !this.account.equals(other.account)) {
        return false;
    }
    if (this.balance!= other.balance) {
        return false;
    }
    return true;
}

BUT WHY I HAVE TO OVVERIDE EQUALS()

但为什么我必须 OVVERIDE EQUALS()

回答by johnchen902

You need to overrides equals

你需要覆盖 equals

@Override
public boolean equals(Object obj) {
    if (!(obj instanceof Account))
        return false;
    Account that = (Account) obj;
    return (account == null ? that.account == null : account
            .equals(that.account)) && balance == that.balance;
}

I almost forgot to override hashCodewhen overriding equals

覆盖hashCode时我差点忘了覆盖equals

@Override
public int hashCode() {
    int hash = 17;
    hash = 37 * hash + (account == null ? 0 : account.hashCode());
    long l = Double.doubleToLongBits(balance);
    hash = 37 * hash + (int) (l ^ (l >>> 32));
    return hash;
}

回答by Gabriel Negut

You did not override equals. The default equalsimplementation, inherited from Object, returns trueif and only if the two variables point to the same object.

您没有覆盖equals. equals继承自的默认实现当且仅当两个变量指向同一个对象时才Object返回true

Override equalsto check for field equality (and hashCode, if you're at it).

覆盖equals以检查字段是否相等(以及hashCode,如果您正在检查)。

回答by Funkytown

The Object.equals() method is testing to see if the two things being compared are LITERALLY the same object. While a1 and a2 contain the same information, they are different objects in memory.

Object.equals() 方法正在测试以查看被比较的两个事物是否实际上是同一个对象。虽然 a1 和 a2 包含相同的信息,但它们是内存中的不同对象。

If you want to test equality of the information inside your objects you can have the class implement the Comparableinterface and override the compareTomethod.

如果要测试对象内信息的相等性,可以让类实现Comparable接口并覆盖compareTo方法。

回答by Bourne

The implementation in Object class i.e. the default implementation checks the references. So if the references are same it returns true else it returns false.

Object 类中的实现,即默认实现检查引用。因此,如果引用相同,则返回 true,否则返回 false。

回答by fge

Since you don't override .equals()(and if you do, you mustalso override .hashCode()), you use Object's .equals()implementation; and this implementation returns true if and only if the object references are equal (ie, o1 == o2).

由于您没有覆盖.equals()(如果您这样做,您还必须覆盖.hashCode()),因此您使用Object.equals()实现;并且当且仅当对象引用相等(即o1 == o2)时,此实现才返回 true 。

回答by vineet

You need to override Object.equals()method.

您需要覆盖Object.equals()方法。

回答by MaVRoSCy

It would show trueif a1.balance==a2.balance. Note that the equals()compares objects and not their actual values. To be able to compare an Object you have to overwrite the equals()method.

它会显示true如果a1.balance==a2.balance. 请注意,equals()比较对象而不是它们的实际值。为了能够比较对象,您必须覆盖该equals()方法。

See here for more info Comparing two objects using an equals method, Java

有关更多信息,请参见此处使用 equals 方法比较两个对象,Java