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 2005].
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.
...
Unfortunately, in this case it is impossible to extend the Card
class by adding a value or field in the subclass while preserving the 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]. This compliant solution adopts this approach by adding a private card
field to the XCard
class and providing a public viewCard()
method.
...
A 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]:
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.
...
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.
...
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 [API 2006] URI
class documentation:
A
URI
may be either absolute or relative. AURI
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.
...
Additionally, the URI
class performs normalization (removing extraneous path segments like '..') and relativization of paths [API 2006] and [Darwin 2004].
Noncompliant Code Example (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 | ||
---|---|---|
| ||
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; } |
...
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].
Risk Assessment
Violating the general contract when overriding the equals()
method can lead to unexpected results.
...
Bibliography
[API 2006] | |
Item 8. Obey the general contract when overriding equals | |
9.2, Overriding the | |
Chapter 3, Classes, Strings, and Arrays, The Object Class (Equality) | |
[Sun 2006] | Determining If Two Keys Are Equal (JCA Reference Guide) |
More Joy of Sets |
...