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

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

问题描述

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

I constructed 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,为什么它为false?我错了吗?

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

推荐答案

== 比较对象引用,以查看两个操作数是否指向同一个对象(而不是等效的对象,相同对象)。

== 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 。正如 equals 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天全站免登陆