LinkedHashMap 保持有序迭代原理
来源:互联网 发布:绿盟笔试题python 编辑:程序博客网 时间:2024/05/21 10:04
之前一直有这个疑问,今天有时间就把源码看了看终于知道了原理。分享给大家也做笔记自己可以随后查看�?br style="box-sizing: inherit; -webkit-tap-highlight-color: transparent;">
linkedHashMap entry 继承了hashMap.Entry 然后定义了一个before与after用来存储当前key的上一个值引用和下一个值的引用。然后再addBefore的时候,把上一个值设置成当前对象引用。因为现在还不知道下一个是什么,所以默认也是当前对象引用�?/p>
*/ private static class Entry<K,V> extends 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<T> implements 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 0
- LinkedHashMap 保持有序迭代原理
- LinkedHashMap按存放顺序迭代
- LinkedHashMap如何实现迭代时有序
- 有序Map使用,LinkedHashMap
- HashMap无序 LinkedHashMap有序
- 有序的map LinkedHashMap
- java 有序map: LinkedHashMap
- 有序的map LinkedHashMap
- Java LinkedHashMap 有序
- 有序的map LinkedHashMap
- LinkedHashMap 原理
- 有序的Map集合--LinkedHashMap
- 保持List有序
- python字典保持有序
- 习题 6.2-5 保持堆的性质 (迭代)
- LinkedHashMap的实现原理
- LinkedHashMap的实现原理
- LinkedHashMap的实现原理
- 41. Spring Boot 使用Java代码创建Bean并注册到Spring中【从零开始学Spring Boot】
- CircleGradientRadioLayout
- Httpclient_post解析
- shell 当前目录检测文件是否为空并删除
- 敏感度、特异性:TP TN FP FN sensitivity Accuracy
- LinkedHashMap 保持有序迭代原理
- 在eclipse与myeclipse中创建user library的方式。
- Android Notification(通知)
- 42. Spring Boot多数据源【从零开始学Spring Boot】
- jquery checkBox undefined 和hibernate 联合主键的注意事项 集合转数组 数组转集合 map list 数组 判空 问题
- HttpURLConnection 解析
- Android逆向基础笔记—Dalvik字节码小记_const/4 v2, 0x1
- 导航栏
- 清理plug and play 和 Disk Controller