使用 .equals() 和 == 运算符比较两个对象 [英] Compare two objects with .equals() and == operator

查看:31
本文介绍了使用 .equals() 和 == 运算符比较两个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用一个 String 字段构造了一个类.然后我创建了两个对象,我也必须使用 == 运算符和 .equals() 来比较它们.这是我所做的:

I constructed a class with one String field. Then I created two objects and I have to compare them using == operator and .equals() too. Here's what I've done:

public class MyClass {

    String a;

    public MyClass(String ab) {
        a = ab;
    }

    public boolean equals(Object object2) {
        if(a == object2) { 
            return true;
        }
        else return false;
    }

    public boolean equals2(Object object2) {
        if(a.equals(object2)) {
            return true;
        }
        else return false;
    }



    public static void main(String[] args) {

        MyClass object1 = new MyClass("test");
        MyClass object2 = new MyClass("test");

        object1.equals(object2);
        System.out.println(object1.equals(object2));

        object1.equals2(object2);
        System.out.println(object1.equals2(object2));
    }


}

编译后,结果显示两次错误.如果两个对象有相同的字段——test",为什么会报错?

After compile it shows two times false as a result. Why is it false if the two objects have the same fields - "test"?

推荐答案

== 比较对象引用,它检查两个操作数是否指向同一个对象(不等价 对象,相同 对象).

== compares object references, it checks to see if the two operands point to the same object (not equivalent objects, the same object).

如果你想比较字符串(看它们是否包含相同的字符),你需要使用equals来比较字符串.

If you want to compare strings (to see if they contain the same characters), you need to compare the strings using equals.

在您的情况下,如果字符串匹配,MyClass 的两个实例确实被认为是相等的,则:

In your case, if two instances of MyClass really are considered equal if the strings match, then:

public boolean equals(Object object2) {
    return object2 instanceof MyClass && a.equals(((MyClass)object2).a);
}

...但通常,如果您要定义一个类,那么等效性不仅仅是单个字段的等效性(在本例中为 a).

...but usually if you are defining a class, there's more to equivalency than the equivalency of a single field (a in this case).

旁注:如果您覆盖 equals,您几乎总是需要覆盖 hashCode.正如它在 等于 JavaDoc:

Side note: If you override equals, you almost always need to override hashCode. As it says in the equals JavaDoc:

请注意,每当重写此方法时,通常都需要重写hashCode 方法,以维护hashCode 方法的一般约定,其中规定等于对象必须具有相同的哈希码.

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

这篇关于使用 .equals() 和 == 运算符比较两个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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