Preface

  "The code is more what you’d call guidelines than actual rules" – truer words were never spoken. It’s important when writing code to understand what are vague "guidelines" that should be followed but can be broken or fudged, and what are crisp "rules" that have serious negative consequences for correctness and robustness. I often get questions about the rules and guidelines for hashCode, so I thought I might summarize them here.

Rule: equal items have equal hashes:

  If two objects are equal then they must have the same hash code; or, equivalently, if two objects have different hash codes then they must be unequal.

  The reasoning here is straightforward. Suppose two objects were equal but had different hash codes. If you put the first object in the java set or map then it might be put into special bucket of the collection . If you then ask the set whether the second object is a member, it might search another bucket , and not find it.

Guideline: the integer returned by GetHashCode should never change

  Ideally, the hash code of a mutable object should be computed from only fields which cannot mutate, and therefore the hash value of an object is the same for its entire lifetime.

  However, this is only an ideal-situation guideline; the actual rule is:

Rule: the integer returned by GetHashCode must never change while the object is contained in a data structure that depends on the hash code remaining stable

  It is permissible, though dangerous, to make an object whose hash code value can mutate as the fields of the object mutate. If you have such an object and you put it in a hash table then the code which mutates the object and the code which maintains the hash table are required to have some agreed-upon protocol that ensures that the object is not mutated while it is in the hash table. What that protocol looks like is up to you.

Guideline: the implementation of GetHashCode must be extremely fast

  The whole point of hashCode is to optimize a lookup operation; if the call hashCode is slower than looking through those ten thousand items one at a time, then you haven’t made a performance gain.

  I classify this as a “guideline” and not a “rule” because it is so vague. How slow is too slow? That’s up to you to decide.

Guideline: the distribution of hash codes must be “random”

  By a “random distribution” I mean that if there are commonalities in the objects being hashed, there should not be similar commonalities in the hash codes produced. Suppose for example you are hashing an object that represents the latitude and longitude of a point. A set of such locations is highly likely to be “clustered”; odds are good that your set of locations is, say, mostly houses in the same city, or mostly valves in the same oil field, or whatever. If clustered data produces clustered hash values then that might decrease the number of buckets used and cause a performance problem when the bucket gets really big.

  Again, I list this as a guideline rather than a rule because it is somewhat vague, not because it is unimportant. It’s very important. But since good distribution and good speed can be opposites, it’s important to find a good balance between the two.

  

  hashCode() is designed to do only one thing: balance a hash table. Do not use it for anything else. In particular:

  • It does not provide a unique key for an object; probability of collision is extremely high.
  • It is not of cryptographic strength, so do not use it as part of a digital signature or as a password equivalent
  • It does not necessarily have the error-detection properties needed for checksums.

and so on.

Guidlines and rules About Overwriting hashCode()的更多相关文章

  1. Why we should overwrite the hashCode() when we overwrite the equals()

    Preface Though I have used Java programme language for almost a year, I'm not familiar with a notion ...

  2. Effective Java 09 Always override hashCode when you override equals

    Failure to do so will result in a violation of the general contract for Object.hashCode, which will ...

  3. Recommend ways to overwrite hashCode() in java

    Perface In the former chapter, I talk about topics about hashCode, And I will continue to finish the ...

  4. Effective Java —— 覆盖equals时总要覆盖hashCode

    本文参考 本篇文章参考自<Effective Java>第三版第十一条"Always override hashCode when you override equals&quo ...

  5. Java Map hashCode深究

    [Java心得总结七]Java容器下——Map 在自己总结的这篇文章中有提到hashCode,但是没有细究,今天细究整理一下hashCode相关问题 1.hashCode与equals 首先我们都知道 ...

  6. How to implement equals() and hashCode() methods in Java[reproduced]

    Part I:equals() (javadoc) must define an equivalence relation (it must be reflexive, symmetric, and ...

  7. [Android]使用自定义JUnit Rules、annotations和Resources进行单元测试(翻译)

    以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5795091.html 使用自定义JUnit Rules.ann ...

  8. Favorites of top 10 rules for success

    Dec. 31, 2015 Stayed up to last minute of 2015, 12:00am, watching a few of videos about top 10 rules ...

  9. ArrayList_HashSet的比较及Hashcode分析

    ArrayList_HashSet的比较及Hashcode分析 hashCode()方法的作用   public static void main(String[] args) { Collectio ...

随机推荐

  1. Service的使用

    一.Service的适用范围 1.本地服务(Local Service): 应用程序的内部(单个APP) startServcie  stopService  stopSelf  stopSelfRe ...

  2. Cordova - CordovaError: Promise rejected with non-error: 'ios-deploy was not found

    错误信息: CordovaError: Promise rejected with non-error: 'ios-deploy was not found. Please download, bui ...

  3. 任务查询系统(cqoi2015,bzoj3932)(主席树)

    最近实验室正在为其管理的超级计算机编制一套任务管理系统,而你被安排完成其中的查询部分.超级计算机中的 任务用三元组\((S_i,E_i,P_i)\)描述,\((S_i,E_i,P_i)\)表示任务从第 ...

  4. maven安装以及eclipse配置maven

    详细地址: http://jingyan.baidu.com/article/295430f136e8e00c7e0050b9.html 介绍安装maven,配置Maven环境变量,同时在Eclips ...

  5. 下载apache-tomcat-9.0.17-windows-x64及安装以及用途

    首先我们先去这个网站下载http://www.apache.org/,进入Tomcat,点击Tomcat9 下载64-bit Windows_zip 当我们下载好了之后解压,把多余的文件删除掉,也可以 ...

  6. 剑指offer三十三之丑数

    一.题目 如果一个数的因子中,出去1和本身以外,质数因子只包含2.3和5,则把改数称作丑数(Ugly Number).例如6.8都是丑数,但14不是,因为它包含质数因子7. 习惯上我们把1当做是第一个 ...

  7. 马哥Python 开发9期

    LVS工作模式: 传输层 会话保持:负载均衡(1) session sticky:同一用户调度固定服务器Source IP:LVS sh算法(对某一特定服务而言)Cookie(2) session r ...

  8. linux内核模块的安全

    linux可以动态的加载内核模块,在很多场合可能需要确保加载内核的安全性.如果被攻击者加载恶意内核模块,将会使得内核变得极其危险. 当然,稳妥的做法就是给内核模块进行签名,内核只加载能正确验证的签名. ...

  9. python的 del 函数是删对象还是删引用

    1.首先介绍下python的对象引用 1)Python中不存在传值调用,一切传递的都是对象引用,也可以认为是传址调用.即Python不允许程序员选择采用传值或传引用.Python参数传递采用的是“传对 ...

  10. webpack处理url资源的配置

    webpack处理url资源的配置 1.安装 npm i url-loader -D 2.修改webpack.config.js const path = require('path'); // 启用 ...