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()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值