Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

An object is characterized by its identity (location in memory) and state (actual data). While the '==' operator compares only the identities of two objects (to check if both the references are actually the same object), the equals method defined in java.lang.Object can compare the state as well, when customized by overriding it. The equals method only applies to Objects, not primitives. Also, immutable objects do not need to override equals.

The general usage contract for equals() has been put forth verbatim from the Java specification:

...

Code Block
bgColor#ccccff
public class Card {
  private final int number;

  public Card(int number) {
    this.number = number;
  }

  public boolean equals(Object o) {
  if (!(o instanceof Card))
    return false;
    Card c = (Card)o;
    return c.number == number;
  }
}

class XCard extends Card {
  private String type;
  private Card card;
  
  public XCard(int number, String type) {
    super(number);
    this.type = type;
  }
	  
  public Card viewCard() {
    return card;
  }

  public boolean equals(Object o) {
    if (!(o instanceof XCard))
      return false;
      
      XCard cp = (XCard)o;
         return cp.card.equals(card) && cp.type.equals(type);
  }
	  
  public static void main(String[] args) {
    XCard p1 = new XCard(1, "type1");
    Card p2 = new Card(1);
    XCard p3 = new XCard(1, "type2");
    System.out.println(p1.equals(p2)); //returns false
    System.out.println(p2.equals(p3)); //returns false
    System.out.println(p1.equals(p3)); //returns false
  }
}

...

Risk Assessment

Violating the general contract when overriding the equals() method can lead to unexpected results.

...