使用equals()方法时,为什么具有相同数据的两个对象不相等 [英] Why are two objects with same data not equal while using equals() method

查看:220
本文介绍了使用equals()方法时,为什么具有相同数据的两个对象不相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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));
    }
}

当我执行它时显示false但对象包含变量中的相同数据。解释。

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

推荐答案

因为默认情况下对象基于 equals(Object obj)

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



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

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).


如果你想用你的班级中的 equals()方法检查相等你必须覆盖对象类的equals()方法。

how-to-override-equals-method-in-java ,如下所示:

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

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

你应该随时总是覆盖hashCode()覆盖 Object 类的等于方法。

And you should always override hashCode() whenever overriding equals method of Object class.

#Effective Java,作者Joshua Bloch



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

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()方法时,为什么具有相同数据的两个对象不相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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