Versions Compared

Key

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

Composition or inheritance may be used to create a new class that both encapsulates an existing class and adds one or more fields. When one class extends another in this way, the concept of equality for the subclass may or may not involve its new fields. That is, when comparing two subclass objects for equality, sometimes their respective fields must also be equal, and other times they need not be equal. Depending on the concept of equality for the subclass, the subclass might override equals(). Furthermore, this method must follow the general contract for equals(), as specified by The Java Language Specification (JLS) [JLS 2015].

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 overridden 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 inherited from Object. The default Object.equals() implementation compares only the references and may produce unexpected results.

The equals() method applies only to objects, not to primitives.

Enumerated types have a fixed set of distinct values that may be compared using == rather than 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 lack a requirement for additional functionality need not override the equals() method.

The general usage contract for equals(), as specified by the JLS, 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.

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, the CaseInsensitiveString.equals() method should not attempt to interoperate with objects of the String class.

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

  public CaseInsensitiveString(String s) {
  

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 refer to the same object), the equals method defined in java.lang.Object can compare the state as well, when customized by overriding.

The equals() method only applies to objects, not primitives. Also, immutable objects do not need to override it. There is no need to override equals if checking logical equality is not useful. For example, Enumerated types have a fixed set of distinct values that may be compared using ==}}instead of {{equals(). Note that Enumerated types do have an equals() implementation that uses == internally and this default cannot be overridden. More generally, if a subclass inherits an implementation of equals from a superclass and does not need additional functionality, overriding equals() can be forgone.

Wiki Markup
The general usage contract for {{equals()}} as specified by the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\] says:

  • It is reflexive: For any reference value x, x.equals(x) must return true.
  • 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.
  • 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.
  • 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.
  • For any non-null reference value x, x.equals(null) must return false.

Do not violate any of these five conditions while overriding the equals() method. Mistakes resulting from a violation of the first condition are infrequent; it is consequently omitted from this discussion. The second and third conditions are highlighted. The rule for consistency implies that mutable objects may not satisfy the equals() contract. It is good practice to avoid defining equals() implementations that use unreliable data sources such as IP addresses and caches. The final condition about the comparison with null is typically violated when the equals() code throws an exception instead of returning false. When this constitutes a security vulnerability (in the form of denial of service), it can be trivially fixed by returning false.

Noncompliant Code Example

This noncompliant code example violates the second condition in the contract (symmetry). This requirement means that if one object is equal to another then the other must also be equal to this one. Consider a CaseInsensitiveString class that defines a String and overrides the equals() method. The CaseInsensitiveString knows about ordinary strings but the String class has no idea about case-insensitive strings. As a result, s.equalsIgnoreCase(((CaseInsensitiveString)o).s) returns true but s.equalsIgnoreCase((String)o) always returns false.

Code Block
bgColor#FFCCCC

public final class CaseInsensitiveString {
  private String s;

  public CaseInsensitiveString(String s) {
    if (s == null) {
      throw new NullPointerException();
    } 
    this.s = s;
  }

  // This method violates asymmetrysymmetry
  public boolean equals(Object o) {
    if (o instanceof CaseInsensitiveString) {
      return s.equalsIgnoreCase(((CaseInsensitiveString)o).s);
    }

    if (o instanceof String) {
      return s.equalsIgnoreCase((String)o);
    }
    return false;
  }

  // publicComply static void main(Stringwith MET09-J
  public int hashCode() {/* ... */}

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

Compliant Solution

Do not try to inter-operate with String from within the By operating on String objects, the CaseInsensitiveString.equals() method . The new equals() method is highlighted in this compliant solution.violates the second contract requirement (symmetry). Because of the asymmetry, given a String object s and a CaseInsensitiveString object cis that differ only 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 operate only on instances of the CaseInsensitiveString class, consequently preserving symmetry:

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

  public CaseInsensitiveString(String s) {
    if (s
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 int hashCode() {/* ... */}

  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 violates transitivity though it satisfies the symmetry condition. In the first print statement, the comparison between p1 and p2 returns true, in the second, the comparison between p2 and p3 also returns true but in the third, the comparison between p1 and p3 returns false. This contradicts the transitivity ruledefines an XCard class that extends the Card 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  public int hashCode() {/* ... */}

}

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 int hashCode() {/* ... */}

  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

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

 

...

// 

...

violating 

...

transitivity
  }
}

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 the field type.

Compliant Solution (Delegation)

Unfortunately, in this case it is impossible to extend the Card class by adding a value or field in the subclass while preserving the Java equals() contract. This problem is not specific to the Card class but applies to any class hierarchy that can consider equal instances of distinct subclasses of some superclass. For such cases, use composition rather than inheritance to achieve the desired effect [Bloch 2008], [Liskov 1994], [Cline, C++ Super-FAQ]. It is fundamentally impossible to have a class that both allows arbitrary subclass extensions and permits an equals() method that is reflexive, symmetric, and transitive, as is required by Object.equals(). In the interests of consistency and security, we forgo arbitrary subclass extensions, and assume that {{Card.equals()}} may impose certain restrictions on its subclasses.

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 int hashCode() {/* ... */}

  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
  }
}

Compliant Solution (Class Comparison)

If the Card.equals() method could unilaterally assume that two objects with distinct classes were not equal, it could be used in an inheritance hierarchy while preserving transitivity:

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.getClass() == this.getClass())) {
      return false;
    }

    Card c = (Card)o;
    return c.number == number;
  }

  public int hashCode() {/* ... */}

}

Noncompliant Code Example (Consistency)

A uniform resource locator (URL) specifies both the location of a resource and a method to access it. According to the Java API documentation for Class URL [API 2014]:

Two URL objects are equal if they have the same protocol, reference equivalent hosts, have the same port number on the host, and the same file and fragment of the file.

Two hosts are considered equivalent if both host names can be resolved into the same IP addresses; else if either host name can't be resolved, the host names must be equal without regard to case; or both host names equal to null.

The defined behavior for the equals() method is known to be inconsistent with virtual hosting in HTTP.

Virtual hosting allows a web server to host multiple websites on the same computer, sometimes sharing the same IP address. Unfortunately, this technique was unanticipated when the URL class was designed. Consequently, when two completely different URLs resolve to the same IP address, the URL class considers them to be equal.

Another risk associated with the equals() method for URL objects is that the logic it uses when connected to the Internet differs from that used when disconnected. When connected to the Internet, the equals() method follows the steps described in the Java API; when disconnected, it performs a string compare on the two URLs. Consequently, the URL.equals() method violates the consistency requirement for equals().

Consider an application that allows an organization's employees to access an external mail service via http://mailwebsite.com. The application is designed to deny access to other websites by behaving as a makeshift firewall. However, a crafty or malicious user could nevertheless access an illegitimate website http://illegitimatewebsite.com if it were hosted on the same computer as the legitimate website and consequently shared the same IP address. Even worse, if the legitimate website were hosted on a server in a commercial pool of servers, an attacker could register multiple websites in the pool (for phishing purposes) until one was registered on the same computer as the legitimate website, consequently defeating the firewall.

Code Block
bgColor#FFCCCC
public class Filter {
  public static void main(String[] args) throws MalformedURLException {
    final URL allowed = new URL("http://mailwebsite.com");
    if (!allowed.equals(new URL(args[0]))) {
      throw new SecurityException("Access Denied");
    }
    // Else proceed
  }
}

Compliant Solution (Strings)

This compliant solution compares the string representations of two URLs, thereby avoiding the pitfalls of URL.equals():

Code Block
bgColor#ccccff
public class Filter {
  public static void main(String[] args) throws MalformedURLException {
    final URL allowed = new URL("http://mailwebsite.com");
    if (!allowed.toString().equals(new URL(args[0]).toString())) {
      throw new SecurityException("Access Denied");
    }
    // Else proceed
  }
}

This solution still has problems. Two URLs with different string representation can still refer to the same resource. However, the solution fails safely in this case because the equals() contract is preserved, and the system will never allow a malicious URL to be accepted by mistake.

Compliant Solution (URI.equals())

A Uniform Resource Identifier (URI) contains a string of characters used to identify a resource; this is a more general concept than an URL. The java.net.URI class provides string-based equals() and hashCode() methods that satisfy the general contracts for Object.equals() and Object.hashCode(); they do not invoke hostname resolution and are unaffected by network connectivity. URI also provides methods for normalization and canonicalization that URL lacks. Finally, the URL.toURI() and URI.toURL() methods provide easy conversion between the two classes. Programs should use URIs instead of URLs whenever possible. According to the Java API Class URI documentation [API 2014]:

A URI may be either absolute or relative. A URI string is parsed according to the generic syntax without regard to the scheme, if any, that it specifies. No lookup of the host, if any, is performed, and no scheme-dependent stream handler is constructed.

This compliant solution uses a URI object instead of a URL. The filter appropriately blocks the website when presented with any string other than http://mailwebsite.com because the comparison fails.

Code Block
bgColor#ccccff
public class Filter {
  public static void main(String[] args)
                     throws MalformedURLException, URISyntaxException {
    final URI allowed = new URI("http://mailwebsite.com");
    if (!allowed.equals(new URI(args[0]))) {
      throw new SecurityException("Access Denied");
    }
    // Else proceed
  }
}

Additionally, the URI class performs normalization (removing extraneous path segments such as "..") and relativization of paths [API 2014], [Darwin 2004].

Noncompliant Code Example (java.security.Key)

The method java.lang.Object.equals() by default is unable to compare composite objects such as cryptographic keys. Most Key classes lack an equals() implementation that would override Object's default implementation. In such cases, the components of the composite object must be compared individually to ensure correctness.

This noncompliant code example compares two keys using the equals() method. The comparison may return false even when the key instances represent the same logical key.

Code Block
bgColor#FFCCCC
private static boolean keysEqual(Key key1, Key key2) {
  if (key1.equals(key2)) {
    return true;
  }
  return false;
}

Compliant Solution (java.security.Key)

This compliant solution uses the equals() method as a first test and then compares the encoded version of the keys to facilitate provider-independent behavior. For example, this code can determine whether a RSAPrivateKey and RSAPrivateCrtKey represent equivalent private keys [Sun 2006].

Code Block
bgColor#ccccff
private static boolean keysEqual(Key key1, Key key2) {
  if (key1.equals(key2)) {
    return true;
  }

  if (Arrays.equals(key1.getEncoded(), key2.getEncoded())) {
    return true;
  }

  // More code for different types of keys here.
  // For example, the following code can check if
  // an RSAPrivateKey and an RSAPrivateCrtKey are equal:
  if ((key1 instanceof RSAPrivateKey) &&
      (key2 instanceof RSAPrivateKey)) {
  
    if ((((RSAKey)key1).getModulus().equals(
         ((RSAKey)key2).getModulus())) &&
       (((RSAPrivateKey) key1).getPrivateExponent().equals(
        ((RSAPrivateKey) key2).getPrivateExponent()))) {
      return true;
    }
  }
  return false;
}

Exceptions

MET08-J-EX0: Requirements of this rule may be violated provided that the incompatible types are never 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 when Timestamp and Date objects are used in the same collection or are otherwise intermixed [Bloch 2008].

Risk Assessment

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

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MET08-J

Low

Unlikely

Medium

P2

L3

Automated Detection

ToolVersionCheckerDescription
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

JAVA.COMPARE.CTO.ASSYM
JAVA.IDEF.NOEQUALS
JAVA.IDEF.CTONOEQ
JAVA.IDEF.CTOEQ

Asymmetric compareTo (Java)
Missing Equals Override (Java)
compareTo without equals (Java)
compareTo/equals mismatch (Java)

Parasoft Jtest

Include Page
Parasoft_V
Parasoft_V

CERT.MET08.EQREFLMake sure implementation of Object.equals(Object) is reflexive
SonarQube
Include Page
SonarQube_V
SonarQube_V
S2162"equals" methods should be symmetric and work for subclasses


Related Guidelines

MITRE CWE

CWE-697, Insufficient Comparison

Bibliography


[API 2014]Class URI
Class URL
(method equals())

[Bloch 2008]

Item 8, "Obey the General Contract When Overriding equals"

[Cline, C++ Super-FAQ]

[Darwin 2004]

Section 9.2, "Overriding the equals Method"

[Harold 1997]

Chapter 3, "Classes, Strings, and Arrays," section "The Object Class (Equality)"

[Liskov 1994]

Liskov, B. H.Wing, J. M. (November 1994). A behavioral notion of subtypingACM Trans. Program. Lang. Syst.16 (6). pp. 1811–1841. doi:10.1145/197320.197383. An updated version appeared as CMU technical report: Liskov, BarbaraWing, Jeannette (July 1999). "Behavioral Subtyping Using Invariants and Constraints" (PS).

[Sun 2006]

Determining If Two Keys Are Equal (JCA Reference Guide)

[Techtalk 2007]

"More Joy of Sets"


...

Image Added Image Added Image Added

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
  }
}

Wiki Markup
"There are some classes in the Java platform libraries that do extend an instantiable class and add a value component. For example, {{java.sql.Timestamp}} extends {{java.util.Date}} and adds a nanoseconds field. The {{equals}} implementation for {{Timestamp}} does violate symmetry and can cause erratic behavior if {{Timestamp}} and {{Date}} objects are used in the same collection or are otherwise intermixed." \[[Bloch 08|AA. Java References#Bloch 08]\]

Risk Assessment

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

Rule

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.

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

MET11-J. Understand the difference between overriding and hiding      12. Methods (MET)      MET13-J. Ensure that hashCode() is overridden when equals() is overridden