...
This noncompliant code example violates the second 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 defines a CaseInsensitiveString
class that defines a String
and overrides the equals()
method. The CaseInsensitiveString
class knows about ordinary strings but the String
class has no idea about knowledge of case-insensitive strings. As a resultConsequently, sCaseInsensitiveString.equalsIgnoreCaseequals(((CaseInsensitiveString)o).s)
returns true
but s.equalsIgnoreCase((String)o)
always returns false
)
method should not attempt to interoperate with objects of the String
class.
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 asymmetrysymmetry 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 } } |
Compliant Solution
As a result, a String
object s
and CaseInsensitiveString object cis
that only differ in case, cis.equals(s))
returns true
while s.equals(cis)
returns false
. This violates the second contract requirement (symmetry).
Compliant Solution
Do not try to inter-operate with String
from within the equals()
method. The new equals()
method is highlighted in this compliant solution.
...