...
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.
...
Code Block | ||
---|---|---|
| ||
public final class CaseInsensitiveString {
private String s;
public CaseInsensitiveString(String s) {
if (s == null) {
throw new NullPointerException();
}
this.s = s;
}
// This method violates symmetry
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;
}
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
}
}
|
...
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; } } 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 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 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, 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. |
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 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 |
---|
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. Bibliography#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.
...
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 URLURLs' s string representations, thereby avoiding the pitfalls of URL.equals()
.
Code Block | ||
---|---|---|
| ||
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 safe 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 to use URIs instead of URLs whenever possible. According to the Java API \[[API 2006|AA. Bibliography#API 06]\], {{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.
This compliant solution uses a URI
object instead of a URL
. The filter appropriately blocks the website when present with a string different from http://mailwebsite.com
, because the comparison fails.
...
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]\]. |
Exceptions
Wiki Markup |
---|
*MET12-EX0:* This guideline 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 if {{Timestamp}} and {{Date}} objects are used in the same collection or are otherwise intermixed. \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. |
Risk Assessment
Violating the general contract when overriding the equals()
method can lead to unexpected results.
...