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 customized by overriding to compare the state as well. When a class defines an equals()
method, the provider has accounted for state comparisonit 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
which compares only the references and may produce conterintuitive counter-intuitive results. For example, the classes String
and StringBuffer
should override the Object.equals()
method because they do not provide their own implementation.
The equals()
method only applies to objects, not primitives. There is no need to override the equals
method when checking logical equality is not useful. For example, Enumerated enumerated types have a fixed set of distinct values that may be compared using ==
instead of the equals()
method. Note that Enumerated 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.
Wiki Markup |
---|
The general usage contract for {{equals()}} as specified by the Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\] says 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
.
Never violate any of these conditions requirements when overriding the equals()
method. Mistakes resulting from a violation of the first condition requirements are infrequent; it is consequently omitted from this discussion. The second and third conditions are highlighted below. The rule for consistency consequently no noncompliant code examples are provided for this case. Noncompliant code examples are provided for the second requirement (symmetry) and the third requirement (transitivity). The consistency requirement implies that mutable objects may not satisfy the equals()
contract. Consequently, it is good practice to avoid defining equals()
implementations that use unreliable data sources such as IP addresses and caches. The most common violation of the final condition requirement regarding comparison with null
is equals()
methods whose code throws an exception rather than returning false
. When this constitutes This can constitute a security vulnerability (in the form of denial of service), the . The simple fix solution is to return false
rather than to throw the exception.
Noncompliant Code Example (Symmetry)
This noncompliant code example violates the second condition requirement 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; } public boolean equals(Object o) { return o instanceof CaseInsensitiveString && ((CaseInsensitiveString)o).s.equalsIgnoreCase(s); } 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 violates transitivity though it satisfies the symmetry conditionrequirement. In the first print statement, the comparison between p1
and p2
returns true
, in the second, the comparison between p2
and p3
also returns true
but in the third, the comparison between p1
and p3
returns false
. This contradicts the transitivity rule.
...