您的位置:首页 > 编程语言 > Java开发

Java中equals与hashcode

2017-11-19 21:18 169 查看
在JDK中,有相关约定,当a.equals(b)为true,那么a.hashcode()就必须与b.hashcode()相等,但是如果a.equals(b)为false,a与b的hashcode并没有强制要求不相等,但是正常做法应该a.equals(b)为false,那么a.hashcode也应该!=b.hashcode,因为这样可以提高hash表的性能。

以下是JDK中Object类的hashcode()注释:

The general contract of hashCode is:

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer
need not remain consistent from one execution of an application to another execution of the same application.
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.
It is not required that if two objects are unequal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct
integer results for unequal objects may improve the performance of hash tables.

当然,最重要的一点是,当我们要把对象作为HashMap的key时,或者放到HashSet容器中时,我们必须重写equals()和hashcode()方法,因为我们在put,get时,hashMap不只是比较了hashcode还有equals,只有两者都为true时才会认为是同一对象。

BTW:
在JDK1.7中引入了一个工具类java.util.Objects,日常使用的isNull,equals,compare我们可以使用这个工具类。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: