An object is characterized by its identity (location in memory) and state (actual data). While the ==
operator compares only the identities of two objects (to check if both the references are actually refer to the same object), the equals
method defined in java.lang.Object
can compare the state as well, when customized by overriding it.
The equals
method only applies to objects, not primitives. Also, immutable objects do not need to override equals. There is no need to override equals
if checking logical equality is not useful. Enumerated types are an example. If a subclass inherits an implementation of equals
from a superclass and does not need additional functionality, overriding equals()
can be forgone.
...
- It is reflexive: For any reference value x,
x.equals(x)
must return true. - It is symmetric: For any reference values x and y,
x.equals(y)
must return true if and only if y.equals(x) returns true. - It is transitive: For any reference values x, y, and z, if
x.equals(y)
returns true andy.equals(z)
returns true, thenx.equals(z)
must return true. - It is consistent: For any reference values x and y, multiple invocations of
x.equals(y)
consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified. - For any non-null reference value x,
x.equals(null)
must return false.
...
Do not violate any of these five conditions while overriding the {{equals
}} method. Mistakes resulting from a violation of to the first condition are infrequent; it is consequently omitted from this discussion. The second and third conditions are highlighted. The rule for consistency implies that mutable objects may not satisfy the {{equals
}} contract. It is good practice to avoid defining {{equals()
}} implementations that use unreliable data sources such as IP addresses \[[Bloch 08|AA. Java References#Bloch 08]\] and caches. The final condition about the comparison with {{null
}} is typically violated when the {{equals()
}} code throws an exception instead of returning {{false
}}. Because this does not constitute a security vulnerability, it is beyond the scope of this discussion.
Noncompliant Code Example
This noncompliant code example violates the second condition in the contract (symmetry). This requirement means that if one object is equal to another then the other must also be equal to this one. Consider a CaseInsensitiveString
class that defines a String
and overrides the equals
method. The CaseInsensitiveString
knows about ordinary strings but the String
class has no idea about case-insensitive strings. As a result, s.equalsIgnoreCase(((CaseInsensitiveString)o).s)
returns true
but s.equalsIgnoreCase((String)o)
always returns false
.
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 asymmetry 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 } } |
...
This noncompliant code example violates transitivity though it satisfies the symmetry condition. In the first print statement, the comparison between p1
and p2
returns true
, in the second, the comparison between p2
and p3
returns false
and in the third, the comparison between p1
and p3
returns false
. This is counter intuitive as p1
and p2
must compare equal when they are both equal to a common object. A practical implementation issue is intermingling of java.sql.Timestamp
and java.util.Date
classes. There is a disclaimer about the erratic behavior in the documentation for the Timestamp
class.
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 } } |
...
Wiki Markup |
---|
It is currently not possible to extend an instantiable class (as opposed to an {{abstract}} class) and add a value or field in the subclass while preserving the {{equals}} contract. This implies that composition must be preferred over inheritance. This technique does qualify as a reasonable workaround \[[Bloch 08|AA. Java References#Bloch 08]\]. It can be implemented by giving the {{XCard}} class a private {{card}} field and providing a a {{public}} {{viewCard}} method. |
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; private Card card; public XCard(int number, String type) { super(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"); System.out.println(p1.equals(p2)); //returns false System.out.println(p2.equals(p3)); //returns false System.out.println(p1.equals(p3)); //returns false } } |
...