黑马程序员技术交流社区
标题:
hashCode的一个小总结
[打印本页]
作者:
Linuxgg
时间:
2014-4-14 23:40
标题:
hashCode的一个小总结
搞来搞去的对比,总是发现离不开equals方法,而顺带的就是hashCode...
于是乎都找一找,列一下,看都是怎么算出来的:
首先百度了一下:
什么是哈希码(HashCode)
在Java中,哈希码代表对象的特征。
例如对象 String str1 = “aa”, str1.hashCode= 3104
String str2 = “bb”, str2.hashCode= 3106
String str3 = “aa”, str3.hashCode= 3104
根据HashCode由此可得出str1!=str2,str1==str3
下面给出几个常用的哈希码的算法。
1:Object类的hashCode.返回对象的内存地址经过处理后的结构,由于每个对象的内存地址都不一样,所以哈希码也不一样。
2:String类的hashCode.根据String类包含的字符串的内容,根据一种特殊算法返回哈希码,只要字符串所在的堆空间相同,返回的哈希码也相同。
3:Integer类,返回的哈希码就是Integer对象里所包含的那个整数的数值,例如Integer i1=new Integer(100),i1.hashCode的值就是100 。由此可见,2个一样大小的Integer对象,返回的哈希码也一样。
复制代码
发现不同的对象,hashCode算法也不一样,那到底都是什么呢?本着研究岛国大片的精神,查了一下源码,记在这里,供日后参阅:
Object:
public native int hashCode();
复制代码
------------------------------------- 数字相关 -----------------------------------------------
Byte:
public int hashCode() {
return (int)value;
}
复制代码
Short:
public int hashCode() {
return (int)value;
}
复制代码
Integer:
public int hashCode() {
return value;
}
复制代码
Long:
public int hashCode() {
return (int)(value ^ (value >>> 32));
}
复制代码
Float:
public int hashCode() {
return floatToIntBits(value);
}
复制代码
Double:
public int hashCode() {
long bits = doubleToLongBits(value);
return (int)(bits ^ (bits >>> 32));
}
复制代码
Boolean:
public int hashCode() {
return value ? 1231 : 1237;
}
复制代码
Character:
public int hashCode() {
return (int)value;
}
复制代码
List:
public int hashCode() {
int hashCode = 1;
Iterator<E> i = iterator();
while (i.hasNext()) {
E obj = i.next();
hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
}
return hashCode;
}
复制代码
String:
public int hashCode() {
int h = hash;
int len = count;
if (h == 0 && len > 0) {
int off = offset;
char val[] = value;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
复制代码
Set:
public int hashCode() {
int h = 0;
Iterator<E> i = iterator();
while (i.hasNext()) {
E obj = i.next();
if (obj != null)
h += obj.hashCode();
}
return h;
}
复制代码
从上可以看出来,hash值,是肯定有重复的... 看来判别一个对象,只靠hashCode是不行的
作者:
席杰
时间:
2014-8-17 11:25
学习了,谢谢分享
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2