Wiki Markup |
---|
Composition or inheritance may be used to create a new class that both encapsulates an existing class and adds one or more fields. When aone subclassclass 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. 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 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 that is inherited from Object
. The default Object.equals()
implementation compares only the references and may produce unexpected results.
...
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 also lack a requirement for additional functionality need not override the equals()
method.
The general usage contract for equals()
as specified by the Java Language Specification establishes five requirements:
- It is reflexive: For any reference value
x
,x.equals(x)
must returntrue
. - It is symmetric: For any reference values
x
andy
,x.equals(y)
must returntrue
if and only ify.equals(x)
returnstrue
. - It is transitive: For any reference values
x
,y
, andz
, ifx.equals(y)
returnstrue
andy.equals(z)
returnstrue
, thenx.equals(z)
must returntrue
. - It is consistent: For any reference values
x
andy
, multiple invocations ofx.equals(y)
consistently returntrue
or consistently returnfalse
, provided no information used inequals()
comparisons on the object is modified. - For any non-null reference value
x
,x.equals(null)
must returnfalse
.
...
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.
...
Note that this code also violates rule MET09-J. Classes that define an equals() method must also define a hashCode() method.
...
In this compliant solution, the CaseInsensitiveString.equals()
method is simplified to operate only on instances of the CaseInsensitiveString
class, consequently preserving symmetry. The class also defines also complies with rule {MET09-J. Classes that define an equals() method must also define a hashCode() method] by defining a hashCode()
method.
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 } } |
...
Code Block | ||
---|---|---|
| ||
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; } // Also define 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 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 } } |
In the noncompliant code example, p1
and p2
compare equal and p2
and p3
compare equal, but p1
and p3
compare unequal; this violates , 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
.
...
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. 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. |
...
Noncompliant Code Example (Consistency)
Wiki Markup |
---|
A Uniformuniform Resourceresource Locatorlocator (URL) specifies both the location of a resource and also a method to access it. According to the Java API documentation for Class URLclass {{URL}} \[[API 2006|AA. Bibliography#API 06]\]: |
...
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.
...
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 can could nevertheless access an illegitimate website http://illegitimatewebsite.com
that is if it were hosted on the same computer as the legitimate website and consequently shares shared the same IP address. Even worse, an attacker can could register multiple websites (for phishing purposes) until one is was registered on the same computer, consequently defeating the firewall.
...
This solution still has problems. Two URLs with different string representation can still refer to the same resource. However, the solution fails safesafely in this case because the equals()
contract is preserved, and the system will never allow a malicious URL to be accepted by mistake.
...
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. It is recommended toPrograms should use URIs instead of URLs whenever possible. According to the Java API \[[API 2006|AA. Bibliography#API 06]\] {{URI}} class documentation: |
...
This compliant solution uses a URI
object instead of a URL
. The filter appropriately blocks the website when present presented with a any string different from other than http://mailwebsite.com
because the comparison fails.
Code Block | ||
---|---|---|
| ||
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 } } |
Wiki Markup |
---|
Additionally, the {{URI}} class also performs normalization (removing extraneous path segments like '..') and relativization of paths \[[API 2006|AA. Bibliography#API 06]\] and \[[Darwin 2004|AA. Bibliography#Darwin 04]\]. |
...
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 overrides 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 | ||
---|---|---|
| ||
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; } |
...
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 ifwhen {{Timestamp}} and {{Date}} objects are used in the same collection or are otherwise intermixed \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. |
...
Related Guidelines
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="d51ec3b5bdd223f7-67bd0a8a-40b341ba-a7a49b21-60253869292d5ecc9798f003"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. Bibliography#API 06]] | [method Method | http://java.sun.com/j2se/1.4.2/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="1d38ad23845c2f9b-0ec06c5d-4e654b5e-936c9b02-f2998e76d47b24f1c4e77c8b"><ac:plain-text-body><![CDATA[ | [[Bloch 2008 | AA. Bibliography#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="6fba1f58c361cc19-86fa6bfc-49ed44f5-9c54b1f6-93e673757d6b4ca15200ba0a"><ac:plain-text-body><![CDATA[ | [[Darwin 2004 | AA. Bibliography#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="380c5558d572b0bc-1aa6d5ff-4cc54fe4-82d3b078-91b92d8326810b41e680b1e2"><ac:plain-text-body><![CDATA[ | [[Harold 1997 | AA. Bibliography#Harold 97]] | Chapter 3: , Classes, Strings, and Arrays, The Object Class (equalityEquality) | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5ff9b3efbcece4c3-25f3d986-452c4d1c-99658a46-229ead637b4f50525dc131cf"><ac:plain-text-body><![CDATA[ | [[Sun 2006 | AA. Bibliography#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="a06b4b0a35d5b07e-ef7b0275-408e4718-98639a97-06be820a7ce6ac1a096d9dcd"><ac:plain-text-body><![CDATA[ | [[Techtalk 2007 | AA. Bibliography#Techtalk 07]] | " More Joy of Sets " | ]]></ac:plain-text-body></ac:structured-macro> |
...