Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

Wiki MarkupComposition 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 2005|AA. References#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 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.

...

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

...

Unfortunately, in this case 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. Use composition rather than inheritance to achieve the desired effect \ [[Bloch 2008|AA. References#Bloch 08]\]. This compliant solution adopts this approach by adding a private {{card}} field to the {{XCard}} class and providing a public {{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
  }
}

Noncompliant Code Example (Consistency)

Wiki MarkupA uniform resource locator (URL) specifies both the location of a resource and also a method to access it. According to the Java API documentation for class {{URL}} \[ [API 2006|AA. References#API 06]\]:

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.

...

Compliant Solution (URI.equals())

Wiki MarkupA 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 {{ 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 \ [[API 2006|AA. References#API 06] \] {{URI}} class URI class documentation:

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.

...

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 like '..') and relativization of paths \ [[API 2006|AA. References#API 06] \] and \[ [Darwin 2004|AA. References#Darwin 04]\].

Noncompliant Code Example (java.security.Key)

...

Compliant Solution (java.security.Key)

Wiki MarkupThis 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|AA. References#Sun 06]\].

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-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|AA. References#Bloch 08]\].

Risk Assessment

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

...

MITRE CWE

CWE-697. Insufficient comparison

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="e66d1219-d8a0-4147-b254-508e32b2361a"><ac:plain-text-body><! [CDATA[ [[API 2006AA. References#API 06] ]

[Method equals()

http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)]

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="dac1f79c-1545-4100-aeff-24d1f08ac2c9"><ac:plain-text-body><![CDATA[

[[Bloch 2008

AA. References#Bloch 08]]

Item 8. Obey the general contract when overriding equals

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="d91fd93f-7e58-445a-8536-01e0d40a3076"><ac:plain-text-body><![CDATA[

[[Darwin 2004

AA. References#Darwin 04]]

9.2, Overriding the equals Method

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="47a4d492-706b-4897-a14a-a9f00e985b6c"><ac:plain-text-body><![CDATA[

[[Harold 1997

AA. References#Harold 97]]

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

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="cfb997f0-897f-44fd-95e0-ab58a463e573"><ac:plain-text-body><![CDATA[

[[Sun 2006

AA. References#Sun 06]]

[Determining If Two Keys Are Equal

http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#Determining%20If%20Two%20Keys%20Are%20Equal] (JCA Reference Guide)

]]></ac:plain-text-body></ac:structured-macro>

[Bloch 2008]

Item 8. Obey the general contract when overriding equals

[Darwin 2004]

9.2, Overriding the equals Method

[Harold 1997]

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

[Sun 2006]

Determining If Two Keys Are Equal (JCA Reference Guide)

[Techtalk 2007]

More Joy of Sets

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="24890be6-0415-4431-b328-efa9bb3aa9ba"><ac:plain-text-body><![CDATA[

[[Techtalk 2007

AA. References#Techtalk 07]]

More Joy of Sets

]]></ac:plain-text-body></ac:structured-macro>

...

      05. Methods (MET)      MET09-J. Classes that define an equals() method must also define a hashCode() method