Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does equals(Object obj) do?

Tags:

java

I´ve often found an equals method in different places. What does it actually do? Is it important that we have to have this 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;
    }
}
like image 441
Best Avatar asked Dec 01 '11 08:12

Best


1 Answers

Aside from everything given by Bozho, there are some additional things to be aware of if overriding equals:

  • something.equals(null) must always return false - i.e. null is not equal to anything else. This requirement is taken care of in the second if of your code.

  • if it is true that something == something else, then also something.equals(something else) must also be true. (i.e. identical objects must be equal) The first if of your code takes care of this.

  • .equals SHOULD be symetric for non-null objects, i.e. a.equals(b) should be the same as b.equals(a). Sometimes, this requirement breaks if you are subclassing and overriding equals in the parent-class and in the subclass. Often equals contains code like if (!getClass().equals(other.getClass())) return false; that at least makes sure that a diffrent object type are not equal with each other.

  • If you override equals you also MUST override hashCode such that the following expression holds true: if (a.equals(b)) assert a.hashCode() == b.hashCode(). I.e. the hash code of two objects that are equal to each other must be the same. Note that the reverse is not true: two objects that have the same hash code may or may not be equal to each other. Ususally, this requirement is taken care of by deriving the hashCode from the same properties that are used to determine equality of an object.

In your case, the hashCode method could be:

public int hashCode() {
  return getFirstName().hashCode() +
    getLastName().hashCode() +
    getPhoneHome().hashCode() +
    getCellPhone().hashCode();
}
  • If you implement Comparable that compares two objects if they are smaller, larger, or equal to each other, a.compareTo(b) == 0 should be true if and only if a.equalTo(b) == true

In many IDEs (e.g. Eclipse, IntelliJ IDEA, NetBeans) there are features that generate both equals and hashCode for you, thereby sparing you of tedious and possibly error-prone work.

like image 127
nd. Avatar answered Oct 17 '22 07:10

nd.