Most books do not provide each class with the ability to find out whether two objects of the class have the same value.
public boolean equals(Date pDate) { return iYear==pDate.iYear && iMonth==pDate.iMonth && iDay==pDate.iDay; }If a client attempts to use objects of this class with objects of the Collections API (or Hashtable or Vector), they are in for a shock. None of the following methods will work with that declaration of equals:
Hashtable | contains, containsKey, get, put, remove |
Vector | contains, indexOf |
List | contains, remove, indexOf |
Map | containsKey, containsValue, get, put, remove |
Set | add, contains, remove |
Instead, you need to teach that for the equals method to be useful it needs to have a parameter of type Object. For example, if we are providing an interface called Date and a class called DateImpl, we could declare the following:
public boolean equals(final Object pObject) { if ( ! (pObject instanceof DateImpl) ) { return false; } return iYear==((DateImpl)pObject).iYear && iMonth==((DateImpl)pObject).iMonth && iDay==((DateImpl)pObject).iDay; }
If you declare equals properly, you need also to declare hashCode. There are warnings about this in the documentation of some of these classes. For example, the WWW pages that document java.util.Hashtable states that ‘to successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.’
public int hashCode() { return iYear*416 + iMonth*32 + iDay; }
The informal analysis of when specific aspects of Java are taught by various books gave the following results:
Arnow Bishop Deitel Garside Horstmann Koffman Lewis Smith Cornelius Does the book suggest that equals always be declared? lost no no no 339:60 no lost lost 219:47 Does the book teach the proper declaration of equals? lost no no no 340:60 no no wrong 221:47 Does the book teach the proper declaration of hashCode? no no no no no no no 311:72 223:47