LinkHashMap源碼詳解

一、成員變量

private transient Entry<K,V> header;//循環雙向鏈表的頭

二、構造方法

LinkHashMap的構造方法和HashMap的構造方法一樣,但是重寫init()方法;

    @Override
    void init() {
        header = new Entry<>(-1, null, null, null);
        //將元素的前驅和後續都指向自己,圖解
        header.before = header.after = header;
    }

這裏寫圖片描述

put方法

put方法和hashMap的方法大致相似,不過重寫了addEntry方法,主要介紹addEntry方法

    void addEntry(int hash, K key, V value, int bucketIndex) {
        //調用父類的addEntry方法,但是重寫了createEntry方法
        super.addEntry(hash, key, value, bucketIndex);

        // Remove eldest entry if instructed
        Entry<K,V> eldest = header.after;
        if (removeEldestEntry(eldest)) {
            removeEntryForKey(eldest.key);
        }
    }


    void createEntry(int hash, K key, V value, int bucketIndex) {
        HashMap.Entry<K,V> old = table[bucketIndex];
        Entry<K,V> e = new Entry<>(hash, key, value, old);
        table[bucketIndex] = e;
        //主要看這個方法,把鏈表頭傳進去
        e.addBefore(header);
        size++;
    }
 private void addBefore(Entry<K,V> existingEntry) {
            //圖解
            after  = existingEntry;
            before = existingEntry.before;
            before.after = this;
            after.before = this;
        }

第一次添加新的結點不是很好體現出循環雙向鏈表
這裏寫圖片描述
第二次添加新的結點
這裏寫圖片描述

remove方法

remove和hashMap的remove的方法很像,不過LinkedHashMap重寫了e.recordRemoval(this);這個方法

        private void remove() {
            //下面的代碼相當於這樣的,加個this比較好理解
            //this.before.after = this.after;
            //this.after.before = this.before;

            //源碼
            before.after = after;
            after.before = before;
        }

這裏寫圖片描述

迭代器

    private abstract class LinkedHashIterator<T> implements Iterator<T> {
        Entry<K,V> nextEntry    = header.after;
        Entry<K,V> lastReturned = null;
        int expectedModCount = modCount;

        //如果結點不等於鏈表頭,那麼說明還有元素
        public boolean hasNext() {
            return nextEntry != header;
        }

        public void remove() {
            if (lastReturned == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();

            LinkedHashMap.this.remove(lastReturned.key);
            lastReturned = null;
            expectedModCount = modCount;
        }

        Entry<K,V> nextEntry() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (nextEntry == header)
                throw new NoSuchElementException();

            Entry<K,V> e = lastReturned = nextEntry;
            nextEntry = e.after;
            return e;
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章