...
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.
...
By operating on String
objects, the CaseInsensitiveString.equals()
method 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 | ||
---|---|---|
| ||
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 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 the field type
.
Compliant Solution
Wiki Markup |
---|
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 {{viewCard()}} method. |
Code Block | ||
---|---|---|
| ||
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 Markup |
---|
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|AA. References#API 06]\]: |
...
Code Block | ||
---|---|---|
| ||
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 two URLs' string representations, thereby avoiding the pitfalls of URL.equals()
.
...
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()
)
Wiki Markup |
---|
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|AA. References#API 06]\] {{URI}} class documentation: |
...
Wiki Markup |
---|
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
)
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.
...
Code Block | ||
---|---|---|
| ||
private static boolean keysEqual(Key key1, Key key2) { if (key1.equals(key2)) { return true; } return false; } |
Compliant Solution (java.security.Key
)
Wiki Markup |
---|
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|AA. References#Sun 06]\]. |
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; } |
Exceptions
Wiki Markup |
---|
*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.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MET08-J | low | unlikely | medium | P2 | L3 |
Related Guidelines
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="60c3981ff53b5e03-cc019368-49794d3c-99fba9e9-d8b1fa9f75be806363d49b81"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. References#API 06]] | [Method | 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="20637ea71bb87c96-15740d20-4ecf48b3-8b46b590-c77a2da5df45593108eee6ed"><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="98601cc18d44e36e-966f61de-446a4aa9-8a5c9236-53f938e88089dbabff6592f8"><ac:plain-text-body><![CDATA[ | [[Darwin 2004 | AA. References#Darwin 04]] | 9.2, Overriding the | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="ef75c7e62a928b67-dc880c0c-493d4ff7-8973b056-9a78148a2c2bc994ddab11d5"><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="3290f7d4c440d8af-5b298328-4b9444ae-b5e48bea-e8ee7f6300fd3b4b8b32fe26"><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> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="55cd63b4955dafc4-959f13e7-40914266-a9acae35-a6450ce21ff376b298797b42"><ac:plain-text-body><![CDATA[ | [[Techtalk 2007 | AA. References#Techtalk 07]] | More Joy of Sets | ]]></ac:plain-text-body></ac:structured-macro> |
...