为什么这两个Java对象不相等? [英] Why these two Java objects do not equals?

查看:67
本文介绍了为什么这两个Java对象不相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一些代码,发现对象等于一个对象-这是一个琐碎的问题,但不了解默认等于的工作原理.

I was make some code and found that objects ar eno equals - it is trivial question but not understand how default equals works.

class A {
    String id;
    public A(String id) {
        this.id = id;
    }

    public static void main(String args[])
    {
        A a = new A("1");
        A b = new A("1");
        System.out.println(a.id);
        System.out.println(b.id);
        System.out.println(a.equals(b));
    }
}

结果是:

1
1
false

但是我想拥有 a.equals(b)== true 为什么它是 false ?

But I want to have a.equals(b) == true why it is false?

推荐答案

您的类当前仅扩展了 Object 类,并且在Object类中的 equals 方法看起来像这样

Your class currently extends only Object class and in Object class equals method looks like this

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

您需要重写此方法,例如

What you need is to override this method, for example like this

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    A other = (A) obj;
    if (id == other.id)
        return true;
    if (id == null)
        return false;
    if (other.id == null)
        return false;
    if (!this.id.equals(other.id))
        return false;
    return true;
}

此外,当覆盖 equals 时,您可能应该覆盖 hashCode 方法,但这不是您的问题.您可以在此处了解更多信息.

Also when you override equals you probably should override hashCode method, but this is not subject of your question. You can read more about it here.

这篇关于为什么这两个Java对象不相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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