Versions Compared

Key

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

Wiki Markup
Composition may be used to create a new class that encapsulates an existing class, but then adds a value or field, the value of which must be equal for objects of this new class to be equal.  If objects of this new class are equated with objects of the encapsulated class, the new class must define an {{equals()}} method, and this method must follow the general contract for {{equals()}} as specified by the Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\].

An object is characterized both by its identity (location in memory) and by its state (actual data). The == operator compares only the identities of two objects (to check whether the references refer to the same object); the equals method defined in java.lang.Object can be customized by overriding to compare the state as well. When a class defines an equals() method, it implies that the method compares state. When the class lacks a customized equals() method (either locally declared, or inherited from a parent class), it uses the default Object.equals() implementation that is inherited from Object which compares only the references and may produce counter-intuitive results.

The equals() method only applies to objects, not primitives. There is no need to override the equals method when checking logical equality is not useful. For example, enumerated types have a fixed set of distinct values that may be compared using == instead of the equals() method. Note that enumerated types provide an equals() implementation that uses == internally; this default cannot be overridden. More generally, subclasses that both inherit an implementation of equals() from a superclass and also lack a requirement for additional functionality need not override the equals() method.

Wiki MarkupThe general usage contract for {{equals()}} as specified by the Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\] establishes five requirements:

  1. It is reflexive: For any reference value x, x.equals(x) must return true.
  2. It is symmetric: For any reference values x and y, x.equals(y) must return true if and only if y.equals(x) returns true.
  3. It is transitive: For any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) must return true.
  4. It is consistent: For any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.
  5. For any non-null reference value x, x.equals(null) must return false.

Never violate any of these requirements when overriding the equals() method. Mistakes resulting from a violation of the first requirements are infrequent; consequently no noncompliant code examples are provided for this case. Noncompliant code examples are provided for the second requirement (symmetry) and the third requirement (transitivity). The consistency requirement implies that mutable objects may not satisfy the equals() contract. Consequently, it is good practice to avoid defining equals() implementations that use unreliable data sources such as IP addresses and caches. The most common violation of the final requirement regarding comparison with null is equals() methods whose code throws an exception rather than returning false. This can constitute a security vulnerability (in the form of denial of service). The simple solution is to return false rather than to throw the exception.

Noncompliant Code Example (Symmetry)

This noncompliant code example defines a CaseInsensitiveString class that includes a String and overrides the equals() method. The CaseInsensitiveString class knows about ordinary strings but the String class has no knowledge of case-insensitive strings. Consequently, CaseInsensitiveString.equals() method should not attempt to interoperate with objects of the String class.

...

By operating on String objects, the CaseInsensitiveString.equals() method violates the second contract requirement (symmetry). Because of the asymmetry, a String object s and CaseInsensitiveString object cis that only differ in case, cis.equals(s)) returns true while s.equals(cis) returns false.

Compliant Solution

In this compliant solution, the CaseInsensitiveString.equals() method is simplified to only operation on instances of the CaseInsensitiveString class.

Code Block
bgColor#ccccff
public final class CaseInsensitiveString {
  private String s;

  public CaseInsensitiveString(String s) {
    if (s == null) {
      throw new NullPointerException();
    }
    this.s = 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 now
  }
}

Noncompliant Code Example (Transitivity)

This noncompliant code example defines an XCard class that extends the Card class.

...

In the noncompliant code example, p1 and p2 compare equal and p2 and p3 compare equal but p1 and p3 compare unequal; violating the transitivity requirement. The problem is that the Card class has no knowledge of the XCard class and consequently cannot determine that p2 and p3 have different values for type. Unfortunately, it is impossible to extend an instantiable class (as opposed to an abstract class) by adding a value or field in the subclass while preserving the equals() contract.

Compliant Solution

Wiki Markup
Because it is impossible to extend an instantiable class while preserving the {{equals()}} contract, composition must be used instead of inheritance \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. This compliant solution adopts this approach by adding a private {{card}} field to the {{XCard}} class and providing a {{public}} {{viewCard()}} method. 

Code Block
bgColor#ccccff
class XCard {
  private String type;
  private Card card; // Composition
  
  public XCard(int number, String type) {
    card = new Card(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");
    XCard p4 = new XCard(1, "type1");
    System.out.println(p1.equals(p2)); // Prints false
    System.out.println(p2.equals(p3)); // Prints false
    System.out.println(p1.equals(p3)); // Prints false
    System.out.println(p1.equals(p4)); // Prints true
  }
}

Exceptions

Wiki Markup
*MET12-EX1:* This guideline may be violated provided that the incompatible types are not compared.  There are classes in the Java platform libraries (and elsewhere) that extend an instantiable class by adding a value component.  For example, {{java.sql.Timestamp}} extends {{java.util.Date}} and adds a nanoseconds field. The {{equals}} implementation for {{Timestamp}} violates symmetry and can cause erratic behavior if {{Timestamp}} and {{Date}} objects are used in the same collection or are otherwise intermixed." \[[Bloch 2008|AA. Bibliography#Bloch 08]\]

Risk Assessment

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

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

MET12-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.

Bibliography

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

...