点石互动

导航

 

这两个类是java中进行key-value存储、查询的常用类,如果我们学习过哈希算法就会知道key-value查询的效率依赖于如何存储,换句话说,如果存的好,拿出来就容易,存的不好,拿出来就不方便。两个类有很多相似之处,他们之间的关系和区别到底如何,先看看它们两个当中最核心方法put的实现。

1.Hashtable的put方法的实现,以下代码做了注释:

Java代码 复制代码 收藏代码
  1. /**  
  2.  * Hashtable的put方法,是同步的,可以在多线程环境下确保原子性执行,index值的计算过程非常简单,  
  3.  * 但是运气不好的话有可能得到大量重复的index,大量的key-value存储在相同的Entry链表中,从而降  
  4.  * 低了get操作的执行效率  
  5.  */  
  6. public synchronized V put(K key, V value) {   
  7.     // Make sure the value is not null   
  8.     if (value == null) {   
  9.         throw new NullPointerException();   
  10.     }   
  11.   
  12.     // Makes sure the key is not already in the hashtable.   
  13.     Entry tab[] = table;   
  14.        
  15.     //得到哈希值   
  16.     int hash = key.hashCode();   
  17.        
  18.     /* 通过哈希值获取index */  
  19.     int index = (hash & 0x7FFFFFFF) % tab.length;   
  20.        
  21.     /* 遍历Entry链表 */  
  22.     for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {   
  23.         /* 注意这里不仅要比较哈希值还要比较key对象 */  
  24.         if ((e.hash == hash) && e.key.equals(key)) {   
  25.             V old = e.value;   
  26.             e.value = value;   
  27.             return old;   
  28.         }   
  29.     }   
  30.        
  31.     modCount++;   
  32.        
  33.     /* 如果装不下了,就扩充容量,重新获取index */  
  34.     if (count >= threshold) {   
  35.         // Rehash the table if the threshold is exceeded   
  36.         rehash();   
  37.            
  38.         tab = table;   
  39.         index = (hash & 0x7FFFFFFF) % tab.length;   
  40.     }   
  41.   
  42.     /* 如果根据哈希值没找到对应的entry对象,在entry链表末尾加入新的entr对象 */  
  43.     Entry<K,V> e = tab[index];   
  44.     tab[index] = new Entry<K,V>(hash, key, value, e);   
  45.     count++;   
  46.     return null;   
  47. }  

 

posted on 2013-02-11 19:34  点石互动  阅读(175)  评论(0编辑  收藏  举报