HashTable HashMap和LinkedHashMap

(1)关于HashTable和HashMap的区别,在HashMap的源码里有一段话讲得非常清楚。 The  HashMap   class is roughly equivalent to  Hashtable  , except that it is  unsynchronized and permits nulls.也就是 HashMap  不是线程安全的,且允许key和value的值为null。
(2)接下来看看HashMap的具体实现,透过下面的数据结构,知道HashMap就是一个数组,数组元素是一个个链表。
     (a)transient  Entry[]  table ;
     (b)static   class  Entry<K,V>  implements  Map.Entry<K,V> {
              final  K  key ;
             V  value ;
             Entry <K,V>  next  ;
              final   int   hash ;
        }
     Entry保存了key,value,hash的值,同是指向下一个Entry。
     HashMap是如何保存元素的?
     public  V put(K key, V value) {
         if  (key ==  null )
             return  putForNullKey(value);
        //通过这里我们看到在写对象时重载 hashCode()的意义
         int  hash = hash(key.hashCode());
        //计算出将要存放到数组的位置
         int  i = indexFor(hash,  table  . length  );
        //如果不为null,那么进行更新
         for  (Entry<K,V> e =  table [i]; e !=  null ; e = e.  next ) {
            Object k;
             if  (e.  hash  == hash && ((k = e.  key ) == key || key.equals(k))) {
                V oldValue = e.  value ;
                e.  value  = value;
                e.recordAccess(  this );
                 return  oldValue;
            }
        }
         modCount ++;
        //添加新元素
        addEntry(hash, key, value, i);
         return   null ;
    }
(3)最后 来看看LinkedHashMap的具体实现
This implementation differs from  <tt> HashMap   </tt>  in that it maintains a doubly -   linked list running through  all of its entries.  This linked list defines the iteration ordering,  which is normally the order in which keys were inserted into the map  (  <i> insertion   - order   </i> ).
     public   class  LinkedHashMap<K,V>  extends  HashMap<K,V>  implements  Map<K,V>可以看出 LinkedHashMap是 HashMap的子类,透过上面的一段话, LinkedHashMap保留了元素的插入顺序,同时不受重复插入的影响 HashMap肯定是散列函数决定元素顺序。
      LinkedHashMap 包含一个双向链表 private  transient  Entry<K,V>  header ;
具体见 http://zhangshixi.iteye.com/blog/673789


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值