Tuesday, April 1, 2014

Use hash based collections

Frequently we want to use self-defined object in HashMap, HashSet, or HashTable. However, if we did not override hashCode() and equals(), these collections will not perform the way we want.

Take HashMap containsKey() for example, it need to

  1. get the key object's hash code and locate the place where objects with this hashCode is stored
  2. compare with all the objects hold in that locality, figure out wether an equal objects exists
That's why we need hashCode and equals. If we do not override hashCode() and equals(), the one of Object will be called by default, where equals() only returns true when they reference to the same object. For most of the cases, this is not what we actually want.

If equals is overrided, hashCode also need to be overrided such that two equal objects will have the same hash code.
A.equals(B) => A.hashCode() == B.hashCode();



@Override
public int hashCode(){
}

@Override
public boolean equals(Object obj){
}

No comments:

Post a Comment