override equals() and hashCode() methods

Saw the hashCode() method used in the FarmerWolfGoatState (a state representation) implementation, but do not know why there should be such an overriding.

 

equals() and hashCode() are the default methods of java class Object.

 

By default, if two objects are equal, then

 

public boolean equals(Object obj) {
    return (this == obj);
  }

Also, if two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

 

------------------------------------------------

 

What would happen if Integer did not override equals() and hashCode()? Nothing, if we never used an Integer as a key in a HashMap or other hash-based collection. However, if we were to use such an Integer object for a key in a HashMap, we would not be able to reliably retrieve the associated value, unless we used the exact same Integer instance in the get() call as we did in the put() call. This would require ensuring that we only use a single instance of the Integer object corresponding to a particular integer value throughout our program. Needless to say, this approach would be inconvenient and error prone.

 

Why does our root object class need hashCode(), when its discriminating ability is entirely subsumed by that of equals()? The hashCode() method exists purely for efficiency.

 

Deciding whether, and how, to override equals() requires a little more judgment. In the case of simple immutable value classes, such as Integer (and in fact for nearly all immutable classes), the choice is fairly obvious -- equality should be based on the equality of the underlying object state. In the case of Integer, the object's only state is the underlying integer value.

 

------------------------------------------------

 

So sometimes if we want to change the default equality definition of object, and only use their state, instead of every part of ojbect, as the rule to judege their equality, we need to override the equals() method. Then we need also to override hashCode() so as to keep the consistence.

 

It seems to be enough to provide equlas() method, adding another one hashCode() is just in order to improve the efficiency for the for the benefit of hashtables such as those provided by java.util.Hashtable.

 

reference:

http://www.ibm.com/developerworks/java/library/j-jtp05273.html

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#hashCode()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章