Java-Collections Framework学习与总结-LinkedHashMap

来源:互联网 发布:js代码混淆加密工具 编辑:程序博客网 时间:2024/05/14 04:19
前面总结了java.util.HashMap,了解了其内部由散列表实现,每个桶内是一个单向链表。那有没有双向链表的实现呢?双向链表的实现会具备什么特性呢?来看一下HashMap的一个子类——java.util.LinkedHashMap。
        先读了一下源码的注释,首先LinkedHashMap中所有的Entry组成了一个双向链表,该链表定义了内部数据的迭代顺序,通常是按key插入的顺序(最近插入的放到链表的末尾,覆盖操作不会影响链表顺序)。LinkedHashMap还提供了构造方法LinkedHashMap(int,float,boolean),如果第三个参数为true,那么内部数据的迭代顺序是按访问的某种顺序(访问时间由远到近),最近访问的数据会放到链表的末尾。这样的结构很适合建立一个LRU Cache,所以基于LinkedHashMap来构建一个LRU Cache是很方便的(可参见removeEldestEntry方法)。
        对于大部分的操作来说,LinkedHashMap的性能比HashMap稍慢那么一点点(由于维护内部双向链表需要附加一些操作,但总体还是常数时间的)。LinkedHashMap的几种视图的迭代(XXIterator)要比HashMap快一些,由于它可以根据内部的双向链表来迭代,而HashMap需要遍历内部的散列表。
        其他特性继承自HashMap,来看下源码。
Java代码  收藏代码
  1. public class LinkedHashMap<K,V>  
  2.     extends HashMap<K,V>  
  3.     implements Map<K,V>  
  4. {  
  5.   
  6.     private static final long serialVersionUID = 3801124242820219131L;  
  7.   
  8.     /** 
  9.      * The head of the doubly linked list. 
  10.      */  
  11.     private transient Entry<K,V> header;  
  12.   
  13.     /** 
  14.      * The iteration ordering method for this linked hash map: <tt>true</tt> 
  15.      * for access-order, <tt>false</tt> for insertion-order. 
  16.      * 
  17.      * @serial 
  18.      */  
  19.     private final boolean accessOrder;  
  20.   
  21.     /** 
  22.      * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance 
  23.      * with the specified initial capacity and load factor. 
  24.      * 
  25.      * @param  initialCapacity the initial capacity 
  26.      * @param  loadFactor      the load factor 
  27.      * @throws IllegalArgumentException if the initial capacity is negative 
  28.      *         or the load factor is nonpositive 
  29.      */  
  30.     public LinkedHashMap(int initialCapacity, float loadFactor) {  
  31.         super(initialCapacity, loadFactor);  
  32.         accessOrder = false;  
  33.     }  
  34.   
  35.     /** 
  36.      * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance 
  37.      * with the specified initial capacity and a default load factor (0.75). 
  38.      * 
  39.      * @param  initialCapacity the initial capacity 
  40.      * @throws IllegalArgumentException if the initial capacity is negative 
  41.      */  
  42.     public LinkedHashMap(int initialCapacity) {  
  43.     super(initialCapacity);  
  44.         accessOrder = false;  
  45.     }  
  46.   
  47.     /** 
  48.      * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance 
  49.      * with the default initial capacity (16) and load factor (0.75). 
  50.      */  
  51.     public LinkedHashMap() {  
  52.     super();  
  53.         accessOrder = false;  
  54.     }  
  55.   
  56.     /** 
  57.      * Constructs an insertion-ordered <tt>LinkedHashMap</tt> instance with 
  58.      * the same mappings as the specified map.  The <tt>LinkedHashMap</tt> 
  59.      * instance is created with a default load factor (0.75) and an initial 
  60.      * capacity sufficient to hold the mappings in the specified map. 
  61.      * 
  62.      * @param  m the map whose mappings are to be placed in this map 
  63.      * @throws NullPointerException if the specified map is null 
  64.      */  
  65.     public LinkedHashMap(Map<? extends K, ? extends V> m) {  
  66.         super(m);  
  67.         accessOrder = false;  
  68.     }  
  69.   
  70.     /** 
  71.      * Constructs an empty <tt>LinkedHashMap</tt> instance with the 
  72.      * specified initial capacity, load factor and ordering mode. 
  73.      * 
  74.      * @param  initialCapacity the initial capacity 
  75.      * @param  loadFactor      the load factor 
  76.      * @param  accessOrder     the ordering mode - <tt>true</tt> for 
  77.      *         access-order, <tt>false</tt> for insertion-order 
  78.      * @throws IllegalArgumentException if the initial capacity is negative 
  79.      *         or the load factor is nonpositive 
  80.      */  
  81.     public LinkedHashMap(int initialCapacity,  
  82.              float loadFactor,  
  83.                          boolean accessOrder) {  
  84.         super(initialCapacity, loadFactor);  
  85.         this.accessOrder = accessOrder;  
  86.     }  

        像LinkedList一样,内部存在一个表头header来作为双向链表的起点和终点(实际是一个环状)。accessOrder表示两种顺序——true为访问顺序;false为插入顺序。
Java代码  收藏代码
  1. /** 
  2.  * Called by superclass constructors and pseudoconstructors (clone, 
  3.  * readObject) before any entries are inserted into the map.  Initializes 
  4.  * the chain. 
  5.  */  
  6. void init() {  
  7.     header = new Entry<K,V>(-1nullnullnull);  
  8.     header.before = header.after = header;  
  9. }  
  10.   
  11. /** 
  12.  * Transfers all entries to new table array.  This method is called 
  13.  * by superclass resize.  It is overridden for performance, as it is 
  14.  * faster to iterate using our linked list. 
  15.  */  
  16. void transfer(HashMap.Entry[] newTable) {  
  17.     int newCapacity = newTable.length;  
  18.     for (Entry<K,V> e = header.after; e != header; e = e.after) {  
  19.         int index = indexFor(e.hash, newCapacity);  
  20.         e.next = newTable[index];  
  21.         newTable[index] = e;  
  22.     }  
  23. }  
  24.   
  25.   
  26. /** 
  27.  * Returns <tt>true</tt> if this map maps one or more keys to the 
  28.  * specified value. 
  29.  * 
  30.  * @param value value whose presence in this map is to be tested 
  31.  * @return <tt>true</tt> if this map maps one or more keys to the 
  32.  *         specified value 
  33.  */  
  34. public boolean containsValue(Object value) {  
  35.     // Overridden to take advantage of faster iterator  
  36.     if (value==null) {  
  37.         for (Entry e = header.after; e != header; e = e.after)  
  38.             if (e.value==null)  
  39.                 return true;  
  40.     } else {  
  41.         for (Entry e = header.after; e != header; e = e.after)  
  42.             if (value.equals(e.value))  
  43.                 return true;  
  44.     }  
  45.     return false;  
  46. }  

        还记得HashMap中的钩子方法init(),这里覆盖了init方法,在里面进行了双向链表的初始化。另外覆盖了transfer和containsValue方法,里面采用对链表的遍历,提高了一点儿性能。
        接下来先看一下LinkedHashMap中Entry的代码。
Java代码  收藏代码
  1.    /** 
  2.     * LinkedHashMap entry. 
  3.     */  
  4.    private static class Entry<K,V> extends HashMap.Entry<K,V> {  
  5.        // These fields comprise the doubly linked list used for iteration.  
  6.        Entry<K,V> before, after;  
  7.   
  8. Entry(int hash, K key, V value, HashMap.Entry<K,V> next) {  
  9.            super(hash, key, value, next);  
  10.        }  
  11.   
  12.        /** 
  13.         * Removes this entry from the linked list. 
  14.         */  
  15.        private void remove() {  
  16.            before.after = after;  
  17.            after.before = before;  
  18.        }  
  19.   
  20.        /** 
  21.         * Inserts this entry before the specified existing entry in the list. 
  22.         */  
  23.        private void addBefore(Entry<K,V> existingEntry) {  
  24.            after  = existingEntry;  
  25.            before = existingEntry.before;  
  26.            before.after = this;  
  27.            after.before = this;  
  28.        }  
  29.   
  30.        /** 
  31.         * This method is invoked by the superclass whenever the value 
  32.         * of a pre-existing entry is read by Map.get or modified by Map.set. 
  33.         * If the enclosing Map is access-ordered, it moves the entry 
  34.         * to the end of the list; otherwise, it does nothing. 
  35.         */  
  36.        void recordAccess(HashMap<K,V> m) {  
  37.            LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;  
  38.            if (lm.accessOrder) {  
  39.                lm.modCount++;  
  40.                remove();  
  41.                addBefore(lm.header);  
  42.            }  
  43.        }  
  44.   
  45.        void recordRemoval(HashMap<K,V> m) {  
  46.            remove();  
  47.        }  
  48.    }  

        重点看下recordAccess和recordRemoval方法。在分析总结HashMap的时候见过这两个钩子方法,在HashMap里,添加或者修改一个数据时(put),会调用recordAccess;删除一个数据时会调用recordRemoval。
        LinkedHashMap的Entry里覆盖了这两个方法。在recordAccess里,如果accessOrder为true,说明是按访问顺序,那么改变双向链表的结构,把当前访问的Entry删掉,添加到链表的末尾。而在recordRemoval里则是从链表中删除当前的Entry。
        那么看下访问方法有什么变化。
Java代码  收藏代码
  1. /** 
  2.  * Returns the value to which the specified key is mapped, 
  3.  * or {@code null} if this map contains no mapping for the key. 
  4.  * 
  5.  * <p>More formally, if this map contains a mapping from a key 
  6.  * {@code k} to a value {@code v} such that {@code (key==null ? k==null : 
  7.  * key.equals(k))}, then this method returns {@code v}; otherwise 
  8.  * it returns {@code null}.  (There can be at most one such mapping.) 
  9.  * 
  10.  * <p>A return value of {@code null} does not <i>necessarily</i> 
  11.  * indicate that the map contains no mapping for the key; it's also 
  12.  * possible that the map explicitly maps the key to {@code null}. 
  13.  * The {@link #containsKey containsKey} operation may be used to 
  14.  * distinguish these two cases. 
  15.  */  
  16. public V get(Object key) {  
  17.     Entry<K,V> e = (Entry<K,V>)getEntry(key);  
  18.     if (e == null)  
  19.         return null;  
  20.     e.recordAccess(this);  
  21.     return e.value;  
  22. }  

        访问方法中调用了Entry的recordAccess方法。
Java代码  收藏代码
  1.    /** 
  2.     * This override alters behavior of superclass put method. It causes newly 
  3.     * allocated entry to get inserted at the end of the linked list and 
  4.     * removes the eldest entry if appropriate. 
  5.     */  
  6.    void addEntry(int hash, K key, V value, int bucketIndex) {  
  7.        createEntry(hash, key, value, bucketIndex);  
  8.   
  9.        // Remove eldest entry if instructed, else grow capacity if appropriate  
  10.        Entry<K,V> eldest = header.after;  
  11.        if (removeEldestEntry(eldest)) {  
  12.            removeEntryForKey(eldest.key);  
  13.        } else {  
  14.            if (size >= threshold)  
  15.                resize(2 * table.length);  
  16.        }  
  17.    }  
  18.   
  19.    /** 
  20.     * This override differs from addEntry in that it doesn't resize the 
  21.     * table or remove the eldest entry. 
  22.     */  
  23.    void createEntry(int hash, K key, V value, int bucketIndex) {  
  24.        HashMap.Entry<K,V> old = table[bucketIndex];  
  25. Entry<K,V> e = new Entry<K,V>(hash, key, value, old);  
  26.        table[bucketIndex] = e;  
  27.        e.addBefore(header);  
  28.        size++;  
  29.    }  
  30.   
  31.    /** 
  32.     * Returns <tt>true</tt> if this map should remove its eldest entry. 
  33.     * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after 
  34.     * inserting a new entry into the map.  It provides the implementor 
  35.     * with the opportunity to remove the eldest entry each time a new one 
  36.     * is added.  This is useful if the map represents a cache: it allows 
  37.     * the map to reduce memory consumption by deleting stale entries. 
  38.     * 
  39.     * <p>Sample use: this override will allow the map to grow up to 100 
  40.     * entries and then delete the eldest entry each time a new entry is 
  41.     * added, maintaining a steady state of 100 entries. 
  42.     * <pre> 
  43.     *     private static final int MAX_ENTRIES = 100; 
  44.     * 
  45.     *     protected boolean removeEldestEntry(Map.Entry eldest) { 
  46.     *        return size() > MAX_ENTRIES; 
  47.     *     } 
  48.     * </pre> 
  49.     * 
  50.     * <p>This method typically does not modify the map in any way, 
  51.     * instead allowing the map to modify itself as directed by its 
  52.     * return value.  It <i>is</i> permitted for this method to modify 
  53.     * the map directly, but if it does so, it <i>must</i> return 
  54.     * <tt>false</tt> (indicating that the map should not attempt any 
  55.     * further modification).  The effects of returning <tt>true</tt> 
  56.     * after modifying the map from within this method are unspecified. 
  57.     * 
  58.     * <p>This implementation merely returns <tt>false</tt> (so that this 
  59.     * map acts like a normal map - the eldest element is never removed). 
  60.     * 
  61.     * @param    eldest The least recently inserted entry in the map, or if 
  62.     *           this is an access-ordered map, the least recently accessed 
  63.     *           entry.  This is the entry that will be removed it this 
  64.     *           method returns <tt>true</tt>.  If the map was empty prior 
  65.     *           to the <tt>put</tt> or <tt>putAll</tt> invocation resulting 
  66.     *           in this invocation, this will be the entry that was just 
  67.     *           inserted; in other words, if the map contains a single 
  68.     *           entry, the eldest entry is also the newest. 
  69.     * @return   <tt>true</tt> if the eldest entry should be removed 
  70.     *           from the map; <tt>false</tt> if it should be retained. 
  71.     */  
  72.    protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {  
  73.        return false;  
  74.    }  

        这里覆盖了父类的addEntry方法,当添加一个数据时,首先调用createEntry方法,该方法也做了重写,加入了维护链表的逻辑,把新加的数据放到了表尾。然后在addEntry方法中有一个判断——通过调用removeEldestEntry方法来决定是否删除最老的(最长时间未访问的)数据。如果是,删除表头的数据;否则,判断是否需要扩容。所以子类可以覆盖removeEldestEntry方法来达到删除最老数据的目的,这在实现一个Cache的时候是非常有用的。
        其余的代码也很容易看懂了,LinkedHashMap就总结到这儿。
0 0