LinkedHashMap 保持有序迭代原理

之前一直有这个疑问,今天有时间就把源码看了看终于知道了原理。分享给大家也做笔记自己可以随后查看�?br style="box-sizing: inherit; -webkit-tap-highlight-color: transparent;">

linkedHashMap entry 继承了hashMap.Entry 然后定义了一个before与after用来存储当前key的上一个值引用和下一个值的引用。然后再addBefore的时候,把上一个值设置成当前对象引用。因为现在还不知道下一个是什么,所以默认也是当前对象引用�?/p>

  */
    private static class Entry<K,Vextends HashMap.Entry<K,V{
        // These fields comprise the doubly linked list used for iteration.
        Entry<K,V> before, after;

        Entry(int hash, K key, V value, HashMap.Entry<K,V> next) {
            super(hash, key, value, next);
        }


        /**
         * Inserts this entry before the specified existing entry in the list.
         */
        private void addBefore(Entry<K,V> existingEntry) {
            after  = existingEntry;
            before = existingEntry.before;
            before.after = this;
            after.before = this;
        }

然后linkedHashMap 定义了一个header变量用来存储第一个值的引用地址,这样迭代的时候就先迭代header,然后根据header 的next找到下一个迭代对象�?/p>

private transient Entry<K,V> header;

然后通过LinkedHashMapIterator的nextEntry方法就能看出nextEntry = e.after�?也就是说nextEntry是上一个值的下一个值。上一个值是当前对象,下一个值也就等于下一个对象,所以这就是它保持有序的原理�?/p>

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

        /**
         * The modCount value that the iterator believes that the backing
         * List should have.  If this expectation is violated, the iterator
         * has detected concurrent modification.
         */
        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;
        }
    }


简单来说,就是第一个赋值是给header,第二次赋值是给header.after�?/p>

然后每次迭代就通过after知道了下一个值,也就保持了有序�?/p>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值