Guidlines and rules About Overwriting hashCode()
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()的更多相关文章
- 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 ...
- 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 ...
- 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 ...
- Effective Java —— 覆盖equals时总要覆盖hashCode
本文参考 本篇文章参考自<Effective Java>第三版第十一条"Always override hashCode when you override equals&quo ...
- Java Map hashCode深究
[Java心得总结七]Java容器下——Map 在自己总结的这篇文章中有提到hashCode,但是没有细究,今天细究整理一下hashCode相关问题 1.hashCode与equals 首先我们都知道 ...
- 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 ...
- [Android]使用自定义JUnit Rules、annotations和Resources进行单元测试(翻译)
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5795091.html 使用自定义JUnit Rules.ann ...
- 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 ...
- ArrayList_HashSet的比较及Hashcode分析
ArrayList_HashSet的比较及Hashcode分析 hashCode()方法的作用 public static void main(String[] args) { Collectio ...
随机推荐
- 程序媛计划——python中级课时1
class1 异常处理 #python会把标准输入的内容当作字符串处理,即使输入的是数字3也会转化为字符串’3’. n1 = raw_input() n2 = raw_input() print n1 ...
- 974. Subarray Sums Divisible by K
Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum ...
- Binary Search Tree-530. Minimum Absolute Difference in BST
Given a binary search tree with non-negative values, find the minimum absolute difference between va ...
- 【北京】安全研究员/工程师-20-35K,人体工程学座椅坐等你来~
招聘地点:北京市西城区 薪资:20-35K 人体工程学座椅,高大上环境坐等你来 [招聘]安全研究员+安全工程师-北京数字观星科技有限公司 北京数字观星科技有限公司成立于2016年9月29日,是一家致力 ...
- Hibernate之mappedBy与@JoinColumn
@JoinColumn所在实体是关系拥有方,name即拥有方对应表到参考表的外键名称. @mappedBy所在实体是关系的被拥有方,value值owner中表示被拥有类的属性. 在单向关系中不需要设置 ...
- Unity色子的投掷与点数的获得(详解)
前几天需要一个色子的投掷并且获得朝上点数的Unity脚本,在网上找了很多,都是一个模子刻出来的. 对于2018版的我来说,网上找的都是很早就弃用了的老版本. 好不容易能运行了,结果并不理想,于是又突发 ...
- J05-Java IO流总结五 《 BufferedInputStream和BufferedOutputStream 》
1. 概念简介 BufferedInputStream和BufferedOutputStream是带缓冲区的字节输入输出处理流.它们本身并不具有IO流的读取与写入功能,只是在别的流(节点流或其他处理流 ...
- 【原创】SSRS (SQL Serve Reporting Service) 访问权限的问题
问题:The permissions granted to user 'TOUCHPOINTMED\sshi' are insufficient for performing this operati ...
- Linux笔记:linux常用命令
文件目录操作 1.展示目录命令 ls # 展示当前目录下的可见文件 ls -a # 展示当前目录下所有的文件(包括隐藏的文件) ls -l # 展示当前目录下文件的详细信息 ll # 展示当前目录下文 ...
- Java保存文本文件
String requestData = "something you want to save"; String saveFilePath = "C:\\Users\\ ...