HashTable HashMap和LinkedHashMap

来源:互联网 发布:java字符串数组长度 编辑:程序博客网 时间:2024/05/17 07:04
(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
原创粉丝点击