关于hashmap中hashcode的问题
http://blog.sina.com.cn/s/blog_7d17f3cc01014dva.html
文章中说道一句话,“在使用自定义对象做key的时候,一定要去实现hashcode方法,不然hashmap就成了纯粹的链表,查找性能非常的慢,添加节点元素也非常的慢”
我非常不理解,主要不理解这个hashcode是怎么算的呢,如果根据对象地址来算的话,也不会出现上面说的问题
common
11 years, 9 months ago
Answers
很有兴趣讨论一下这个hashcode().
- java api里的Object.hashcode():
(This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language.)
看代码可以知道, hashcode()是一个native函数, 但实际JVM会不会直接用对象地址来做hashcode有待探讨, 因为现代的JVM 堆都是分代管理的, 一个Object很可能在一次 GC后改变其对象地址.而对一个对象来说, 其生命周期内的hashcode是不会变的.
- Effective Java里提到自定义hashcode()的recipe(实际上在Eclipse里, 右键-> Source -> Generate hashcode and Equals可以代劳).大概例子这样:
private String s;
private int a;
private short b;
private Date d;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + a;
result = prime * result + b;
result = prime * result + ((d == null) ? 0 : d.hashCode());
result = prime * result + ((s == null) ? 0 : s.hashCode());
return result;
}
In summary, the notion that Object.hashCode() is based on the object's
address is largely a historic artefact that has been obsoleted by the
properties of modern garbage collectors.
icing
answered 11 years, 9 months ago