Versions Compared

Key

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

...

Code Block
bgColor#FFCCCC
public final class Card implements Comparable{
  private String suit;
  private int rank;

  public Card(String s, int r) {
    if (s == null)
      throw new NullPointerException();
    suit = s;
    rank = r;
  }

  public boolean equals(Object o) {
    if (o instanceof Card){
      Card c=(Card)o;
      return suit.equals(c.suit) || (rank == c.rank);
    }
    return false;
  }

  //this method violates its contract
  public int compareTo(Object o){
    if (o instanceof Card){
      Card c=(Card)o;
      if(suit.equals(c.suit)) return 0;
      return c.rank - rank;
    }
    throw new ClassCastException();
  }

  public static void main(String[] args) {
    Card a = new Card("Clubs", 2);
    Card b = new Card("Clubs", 10);
    Card c = new Card("Hearts", 7);
    System.out.println(a.compareTo(b)); //returns 0
    System.out.println(a.compareTo(c)); //returns a negative number
    System.out.println(b.compareTo(c)); //returns a positive number
  }
}

Compliant Solution

Do not try to inter-operate with String from the equals method. The new equals method is highlighted in this compliant solutionMake sure you fulfill the contract, and make sure your corresponding equals method matches with compareTo.

Code Block
bgColor#ccccff
public final class CaseInsensitiveStringCard implements Comparable{
  private String ssuit;
  private int rank;

  public CaseInsensitiveStringCard(String s, int r) {
    if (s == null)
      throw new NullPointerException();
    this.ssuit = s;
  }

  public boolean equals(Object o) {
    return o instanceof CaseInsensitiveString &&
    ((CaseInsensitiveString)o).s.equalsIgnoreCase(s);
  }

  public static void main(String[] args) {
    CaseInsensitiveString cis = new CaseInsensitiveString("Java");
    String s = "java";
    System.out.println(cis.equals(s)); //returns false now
    System.out.println(s.equals(cis)); //returns false nowrank = r;
  }
}

Noncompliant Code Example

This noncompliant example violates transitivity though it follows the symmetry condition. This is because the first two statements print true while the third prints false. A practical implementation issue is intermingling of java.sql.Timestamp and java.util.Date classes. There is a disclaimer about the erratic behavior in the documentation for the Timestamp class.

Code Block
bgColor#FFCCCC
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;
  public XCard(int number, String type) {
    super(number);
    this.type = type;
  }

  public boolean equals(Object o) {
  if (!(o instanceof Card))
    return false;
    //normal Card, do not compare type
    if (!(o instanceof XCard))
      return o.equals(this);
    //It is an XCard, compare type as well
    XCard xc = (XCard)o;
    return super.equals(o) && xc.type == 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 true
    System.out.println(p2.equals(p3)); //returns true
    System.out.println(p1.equals(p3)); //returns false, violating transitivity
  }
}

Compliant Solution

Wiki Markup
"There is simply no way to extend an instantiable class and add an aspect while preserving the equals contract." This implies that composition must be preferred over inheritance in this case. This is done by giving the {{XCard}} class a private {{card}} field and providing a a public {{viewCard}} method. \[[Bloch 08|AA. Java References#Bloch 08]\]

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

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

  public boolean equals(Object o) {
  if (!return suit.equals(c.suit) && (rank == c.rank);
    }
    return false;
  }

  //this method fulfills its contract
  public int compareTo(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)if(suit.equals(c.suit)) return c.rank - rank;
      return suit.compareTo(c.suit);
    }
    throw new ClassCastException();
  }

  public static void main(String[] args) {
    XCardCard p1a = new XCardCard(1"Clubs", "type1"2);
    Card p2b = new Card(1"Clubs", 2);
    XCardCard p3c = new XCardCard(1"Hearts", "type2"7);
    System.out.println(p1a.equalscompareTo(p2b)); //returns false0
    System.out.println(p2a.equalscompareTo(p3c)); //returns falsea negative number
    System.out.println(p1b.equalscompareTo(p3c)); //returns a negative falsenumber
  }
}

TODO: Add condition for hashcode

Risk Assessment

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

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MET30-J

low

unlikely

medium

P2

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[API 06|AA. Java References#API 06]\] [method equals()|http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#equals(java.lang.Object)]
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 8: Obey the general contract when overriding equals
\[[Darwin 04|AA. Java References#Darwin 04]\] 9.2 Overriding the equals method

References

Java APIMET03-J. For methods that return an array or collection prefer returning an empty array or collection over a null value      09. Methods (MET)      MET31-J. Ensure that hashCode() is overridden when equals() is overridden