黑马程序员技术交流社区

标题: hashCode的一个小总结 [打印本页]

作者: Linuxgg    时间: 2014-4-14 23:40
标题: hashCode的一个小总结
搞来搞去的对比,总是发现离不开equals方法,而顺带的就是hashCode...
于是乎都找一找,列一下,看都是怎么算出来的:

首先百度了一下:
  1. 什么是哈希码(HashCode)
  2. 在Java中,哈希码代表对象的特征。
  3. 例如对象 String str1 = “aa”, str1.hashCode= 3104
  4. String str2 = “bb”, str2.hashCode= 3106
  5. String str3 = “aa”, str3.hashCode= 3104
  6. 根据HashCode由此可得出str1!=str2,str1==str3
  7. 下面给出几个常用的哈希码的算法。
  8. 1:Object类的hashCode.返回对象的内存地址经过处理后的结构,由于每个对象的内存地址都不一样,所以哈希码也不一样。
  9. 2:String类的hashCode.根据String类包含的字符串的内容,根据一种特殊算法返回哈希码,只要字符串所在的堆空间相同,返回的哈希码也相同。
  10. 3:Integer类,返回的哈希码就是Integer对象里所包含的那个整数的数值,例如Integer i1=new Integer(100),i1.hashCode的值就是100 。由此可见,2个一样大小的Integer对象,返回的哈希码也一样。
复制代码


发现不同的对象,hashCode算法也不一样,那到底都是什么呢?本着研究岛国大片的精神,查了一下源码,记在这里,供日后参阅:

Object:
  1.   public native int hashCode();
复制代码


-------------------------------------  数字相关     -----------------------------------------------
Byte:
  1.     public int hashCode() {
  2.         return (int)value;
  3.     }
复制代码


Short:
  1.     public int hashCode() {
  2.         return (int)value;
  3.     }
复制代码


Integer:
  1.     public int hashCode() {
  2.         return value;
  3.     }
复制代码


Long:
  1.     public int hashCode() {
  2.         return (int)(value ^ (value >>> 32));
  3.     }
复制代码


Float:
  1.     public int hashCode() {
  2.         return floatToIntBits(value);
  3.     }
复制代码


Double:
  1.     public int hashCode() {
  2.         long bits = doubleToLongBits(value);
  3.         return (int)(bits ^ (bits >>> 32));
  4.     }
复制代码


Boolean:
  1.     public int hashCode() {
  2.         return value ? 1231 : 1237;
  3.     }
复制代码


Character:
  1.     public int hashCode() {
  2.         return (int)value;
  3.     }
复制代码


List:
  1.     public int hashCode() {
  2.         int hashCode = 1;
  3.         Iterator<E> i = iterator();
  4.         while (i.hasNext()) {
  5.             E obj = i.next();
  6.             hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
  7.         }
  8.         return hashCode;
  9.     }
复制代码


String:
  1.      public int hashCode() {
  2.         int h = hash;
  3.         int len = count;
  4.         if (h == 0 && len > 0) {
  5.             int off = offset;
  6.             char val[] = value;

  7.             for (int i = 0; i < len; i++) {
  8.                 h = 31*h + val[off++];
  9.             }
  10.             hash = h;
  11.         }
  12.         return h;
  13.     }
复制代码


Set:
  1.      public int hashCode() {
  2.         int h = 0;
  3.         Iterator<E> i = iterator();
  4.         while (i.hasNext()) {
  5.             E obj = i.next();
  6.             if (obj != null)
  7.                 h += obj.hashCode();
  8.         }
  9.         return h;
  10.     }
复制代码

从上可以看出来,hash值,是肯定有重复的... 看来判别一个对象,只靠hashCode是不行的

作者: 席杰    时间: 2014-8-17 11:25
学习了,谢谢分享




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2