HashMap于LinkedHashMap

HashMap

HashMap是数组加上单链表的形式

# 构造函数

public HashMap() {
    // 4, 0.75f
    this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}

# put

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
// 哈希算法, 不讨论
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
public V put(K key, V value) {
    if (table == EMPTY_TABLE) {
        // 初始化数组容器, 长度为4
        inflateTable(threshold); 
    }
    if (key == null)
        return putForNullKey(value);
    // 计算哈希值
    int hash = sun.misc.Hashing.singleWordWangJenkinsHash(key);
    // int i = 哈希值 & (数组长度-1); 是为了不超出下标
    int i = indexFor(hash, table.length);
    for (HashMapEntry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        // 匹配 对应的key, 和哈希值
        // 如果匹配到覆盖原值
        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;
}

// key 为 NULL 时的方法
private V putForNullKey(V value) {
    // e 赋值为 tabel[0], 可见将 key为 null, 分配到了数组中的0下标
    for (HashMapEntry<K,V> e = table[0]; e != null; e = e.next) {
        // e 不为空, 并且key == null时, 覆盖旧value
        if (e.key == null) {
            V oldValue = e.value;
            e.value = value;
            // 给子类重写, 空方法
            e.recordAccess(this);
            return oldValue;
        }
    }
    modCount++;
    // int hash, K key, V value, int bucketIndex
    addEntry(0, null, value, 0);
    return null;
}

// 给链表添加元素
void addEntry(int hash, K key, V value, int bucketIndex) {
    // 当存储的元素 >= 阈值(默认为3) 并且数组当前下标中的元素不等于空
    if ((size >= threshold) && (null != table[bucketIndex])) {
        // 以原数组长度的2倍扩容
        resize(2 * table.length);
        hash = (null != key) ? sun.misc.Hashing.singleWordWangJenkinsHash(key) : 0;
        bucketIndex = indexFor(hash, table.length);
    }

    createEntry(hash, key, value, bucketIndex);
}
// bucketIndex为要放进容器的下标
// 创建 Entry插入到 table数组 bucketIndex下标链表中的头部
void createEntry(int hash, K key, V value, int bucketIndex) {
    HashMapEntry<K,V> e = table[bucketIndex];
    // 哈希值, key, value, next指针
    table[bucketIndex] = new HashMapEntry<>(hash, key, value, e);
    size++;
}
// 扩容数组
void resize(int newCapacity) {
    HashMapEntry[] oldTable = table;
    int oldCapacity = oldTable.length;
    if (oldCapacity == MAXIMUM_CAPACITY) {
        threshold = Integer.MAX_VALUE;
        return;
    }

    HashMapEntry[] newTable = new HashMapEntry[newCapacity];
    transfer(newTable);
    table = newTable;
    threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
// 将原有数据迁移到扩容后的数组当中
void transfer(HashMapEntry[] newTable) {
    int newCapacity = newTable.length;
    // 外不循环, 遍历远table元素
    for (HashMapEntry<K,V> e : table) {
        // 内部循环, 遍历table元素中的链表
        while(null != e) {
            HashMapEntry<K,V> next = e.next;
            // 根据新的数组长度重新计算下标
            int i = indexFor(e.hash, newCapacity);
            // 相当于将 Node e插入到当前下标链表中的头部
            e.next = newTable[i];
            newTable[i] = e;
            e = next;
        }
    }
}

# get

public V get(Object key) {
    if (key == null)
        return getForNullKey();
    // 根据key 获取对应的 Entry
    Map.Entry<K,V> entry = getEntry(key);

    return null == entry ? null : entry.getValue();
}

// 获取 key 为 NULL的 value
private V getForNullKey() {
    if (size == 0) {
        return null;
    }
    // 在 下标为0的 链表中循环查找
    for (HashMapEntry<K,V> e = table[0]; e != null; e = e.next) {
        if (e.key == null)
            return e.value;
    }
    return null;
}

final Map.Entry<K,V> getEntry(Object key) {
    if (size == 0) {
        return null;
    }

    int hash = (key == null) ? 0 : sun.misc.Hashing.singleWordWangJenkinsHash(key);
    // 遍历链表
    for (HashMapEntry<K,V> e = table[indexFor(hash, table.length)];
         e != null;
         e = e.next) {
        Object k;
        // 匹配 哈希值和 key
        if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
            return e;
    }
    return null;
}

# remove

public V remove(Object key) {
    Map.Entry<K,V> e = removeEntryForKey(key);
    return (e == null ? null : e.getValue());
}

final Map.Entry<K,V> removeEntryForKey(Object key) {
    if (size == 0) {
        return null;
    }
    int hash = (key == null) ? 0 : sun.misc.Hashing.singleWordWangJenkinsHash(key);
    int i = indexFor(hash, table.length);
    HashMapEntry<K,V> prev = table[i];
    HashMapEntry<K,V> e = prev;

    while (e != null) {
        HashMapEntry<K,V> next = e.next;
        Object k;
        if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k)))) {
            modCount++;
            size--;
            // prev == e 表明第一次循环就中标
            if (prev == e)
                table[i] = next;
            else
                // 前一个Node 连接 nextNode
                prev.next = next;
            // 子类重写, 空方法
            e.recordRemoval(this);
            return e;
        }
        prev = e;
        e = next;
    }

    return e;
}

# entrySet()

// entrySet() 和 keySet() 都是一个意思
private Set<Map.Entry<K,V>> entrySet0() {
    Set<Map.Entry<K,V>> es = entrySet;
    return es != null ? es : (entrySet = new EntrySet());
}
// EntrySet
public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
    HashMapEntry<K,V>[] tab;
    if (action == null)
        throw new NullPointerException();
    if (size > 0 && (tab = table) != null) {
        int mc = modCount;
        // 外部循环遍历 tab 数组
        for (int i = 0; i < tab.length; ++i) {
            // 内部循环 遍历链表
            // 规则是从 下标 0开始遍历链表, 链表结束后 在遍历下标1 ...
            for (HashMapEntry<K,V> e = tab[i]; e != null; e = e.next) {
                action.accept(e);
                // 等号不成立, 说明出现了并发错误
                if (modCount != mc) {
                    throw new ConcurrentModificationException();
                }
            }
        }
    }
}
// HashIterator
// KeySet 调用 iterator 会调用该方法获取Entry, 在调用getKey
// 规则也和 foreach() 一样也是从下标0开始 遍历
final Map.Entry<K,V> nextEntry() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
    HashMapEntry<K,V> e = next;
    if (e == null)
        throw new NoSuchElementException();

    if ((next = e.next) == null) {
        HashMapEntry[] t = table;
        while (index < t.length && (next = t[index++]) == null)
        ;
    }
    current = e;
    return e;
}

LinkedHashMap

LinkedHashMap继承于HashMap, 利用双向循环链表保证顺序

# init

void init() {
    // 初始化header, before和after都指向自己
    header = new LinkedHashMapEntry<>(-1, null, null, null);
    header.before = header.after = header;
}

# put

void createEntry(int hash, K key, V value, int bucketIndex) {
    HashMapEntry<K,V> old = table[bucketIndex];
    LinkedHashMapEntry<K,V> e = new LinkedHashMapEntry<>(hash, key, value, old);
    table[bucketIndex] = e;
    // 到上面和 HashMap一样, 插入到当前下标链表的头部
    e.addBefore(header);
    size++;
}

// 该方法传入 header
// 如果说双向循环链表中 header为头部, 那么这里就是插入到队尾
private void addBefore(LinkedHashMapEntry<K,V> existingEntry) {
    // 新元素 after 指向 header
    after  = existingEntry;
    // 新元素 before 指向队尾, 也有可能是header
    before = existingEntry.before;
    // 原队尾元素 after 指向新元素
    before.after = this;
    // header.before 指向新元素
    after.before = this;
}
void transfer(HashMapEntry[] newTable) {
    int newCapacity = newTable.length;
    // 因为每个元素之前都有链表关系, 所以这里没有必要双重循环, 数组和链表
    // 元素 e 从header.after开始
    for (LinkedHashMapEntry<K,V> e = header.after; e != header; e = e.after) {
        int index = indexFor(e.hash, newCapacity);
        e.next = newTable[index];
        newTable[index] = e;
    }
}

# remove()

void recordRemoval(HashMap<K,V> m) {
    remove();
}
private void remove() {
    before.after = after;
    after.before = before;
}

# foreach()

public void forEach(BiConsumer<? super K, ? super V> action) {
    if (action == null)
        throw new NullPointerException();
    int mc = modCount;
    // header.after 开始直到 header为止, header不参与
    for (LinkedHashMapEntry<K,V> e = header.after; modCount == mc && e != header; e = e.after)
        action.accept(e.key, e.value);
    if (modCount != mc)
        throw new ConcurrentModificationException();
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容