What does Java – equals (object obj) do?

I often find an equal way in different places What does it actually do? Do we have to have this important in every class?

public boolean equals(Object obj)
    {
    if (obj == this)
    {
        return true;
    }
    if (obj == null)
    {
        return false;
    }
    if (obj instanceof Contact)
    {
        Contact other = (Contact)obj;
        return other.getFirstName().equals(getFirstName()) &&
                other.getLastName().equals(getLastName()) &&
                other.getHomePhone().equals(getHomePhone()) &&
                other.getCellPhone().equals(getCellPhone());

    }
    else
    {
        return false;
    }
}

Solution

It redefines the "equality" of objects

By default (defined in Java. Lang. object), an object is equal to another object only when it is the same instance However, you can provide custom equality logic when overriding it

For example, Java Lang.string defines equality by comparing internal character arrays This is why:

String a = new String("a"); //but don't use that in programs,use simply: = "a"
String b = new String("a");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true

Even if you may not need to test such equality, you use classes For example, list contains(..) And list indexOf(..) Implementation and use of equals(..).

Check whether the Javadoc is equal to (..) Exact contract for method requirements

In many cases, when overriding equals (..) You must also override hashcode () (using the same field) when This is also specified in Javadoc

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>