...
By operating on String
objects, the CaseInsensitiveString.equals()
method violates the second contract requirement (symmetry). Because of the asymmetry, given a String
object s
and a CaseInsensitiveString
object cis
that differ only in case, cis.equals(s))
returns true
while s.equals(cis)
returns false
.
Note that this code also violates MET13-J. Classes that define an equals() method must also define a hashCode() method.
Compliant Solution
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 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
}
}
|
...