java中重写hashcode的作用 何时才要重写hashcode
来源:互联网 发布:软件外包公司发展 编辑:程序博客网 时间:2024/06/04 21:09
hash code是一种编码方式,在Java中,每个对象都会有一个hashcode,Java可以通过这个hashcode来识别一个对象。至于hashcode的具体编码方式,比较复杂(事实上这个编码是可以由程序员重载的),可以参考数据结构书籍。而hashtable等结构,就是通过这个哈希实现快速查找键对象。这是他们的内部联系,但一般编程时无需了解这些,只要知道hashtable实现了一种无顺序的元素排列就可以了。 两个对象值相同(x.equals(y) == true),则一定有相同的hash code。
===============================================================
下面是String类的hashcode方法
/**
* Returns a hash code for this string. The hash code for a
* <code>String</code> object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using <code>int</code> arithmetic, where <code>s[i]</code> is the
* <i>i</i>th character of the string, <code>n</code> is the length of
* the string, and <code>^</code> indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
==============================================================
评论:
1. 在比较一个类的两个对象时,如果你希望采用你自己的规则来判断两者是否相同,就重写hashCode方法,来实现自己的比较逻辑。如果不重写,就是使用默认的hash code来比较。 也就是说重写equals方法时要重写hashcode方法
2. 万分之一的情形:--当数据量大,10亿以上级别,对象经常冲突。--当性能要求高,hashcode内置的散列算法不能满足特殊的数据结构要求。自己根据自己的对象作出特定的散列算法,加速过程,比如有些窗口控件ID甚至改成简单+1达到更快生成。都是极端情况。总之,一般不重写。只是在教学中提出来用于展示原理。
3. 重写是当你所管理的对象是无规律可循或规律异于一般原理,而你自己创造一个规律。例如,如果你所开发的系统在涉及某个区内的身份证号,则前5位不需要作hash,后3位也不用,为了快速检索,自己定义hash函数,只处理其中的某几位。
- java中重写hashcode的作用 何时才要重写hashcode
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- java中重写equals方法要重写hashCode方法
- java重写hashcode的方法
- HashCode的作用 以及重写equals方法为什么要重写HashCode方法?
- 客户机上没装access等office软件,C#做的小软件可以使用access数据库吗?
- QTP自动化测试框架系列一【复合测试框架(Hybrid Test Automation Framework)】
- Js checkbox全选和全不选
- __doPostBack函数
- 实现多选
- java中重写hashcode的作用 何时才要重写hashcode
- 请求因 HTTP 状态 401 失败:Unauthorized
- 网络运营之剑—html语言(表格设置)
- live555源代码分析RTSP服务器实现原理(转)
- 各类IP地址的范围
- SVN分支与合并【收藏】
- .DS_Store Mac下会生成这个文件 而且看不到
- 解决 eclipse tomcat cannot create a server using the selected type
- Android换肤的两种思路