Monday, 11 May 2015

Java: Always override equals() and hashCode() in a class

Necessity of overriding equals():
========================

Case Study:
---------------

My class myCaseInsensitiveString implements equals(o) that does equalsIgnoreCase() and works if 'o' is either a myCaseInsensitiveString or a String instance

Now,
myCaseInsensitiveString cis = new myCaseInsensitiveString("Polish");
String s = "polish";

while cis.equals(s) => true as equals() in myCaseInsensitiveString does equalsIgnoreCase()
s.equals(cis)  => false as equals() in String will not do equalsIgnoreCase()
Hence, symmetric porperty is broken


workaround:
---------------
modify equals(o) in myCaseInsensitiveString so that it works if and only if 'o' is a myCaseInsensitiveString instance.


Necessity of overriding hashCode():
===========================
-- Implementing optimal hash function also boost  the performance
   Ref Link  http://www.javamex.com/tutorials/collections/hash_function_guidelines.shtml
Case Study:
---------------

Suppose a class PhoneNumber doesn't override the hashCode

Map<PhoneNumber, String> m = new HashMap<PhoneNumber, String>();
m.put(new PhoneNumber(707, 867, 5309), "Jenny");

Here, m.get(new PhoneNumber(707, 867, 5309)) may return null
bcause the insertion & retrieval instances of PhoneNumber may return different hash codes, although the instances are equal

Solution : override the hasCode() method in the PhoneNumber Class:

private volatile int hashCode;
@Override public int hashCode() {
          int result = hashCode;
          if (result == 0) {
          result = 17;
          result = 31 * result + areaCode;
          result = 31 * result + prefix;
          result = 31 * result + lineNumber;
          hashCode = result;
}
return result;
}

No comments:

Post a Comment