博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HashMap无序与LinkedHashMap有序
阅读量:4214 次
发布时间:2019-05-26

本文共 1372 字,大约阅读时间需要 4 分钟。

HashMap为什么是无序?

 

HashMap的数据结构是table[entry],entry是一个链表结构,数据的每个元素是一个链表。不同key,但是具有相同hashcode会落在table[hashcode]的链表上

当使用iterator遍历时,使用如下code:

 

final Entry
nextEntry() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); Entry
e = next; if (e == null) throw new NoSuchElementException(); if ((next = e.next) == null) {//如果链表中的最后一个元素则取table中的下一个element中的链表 Entry[] t = table; //HashMap中的table[entry] while (index < t.length && (next = t[index++]) == null) ; } current = e; return e; }
 

 

 

如上代码,顺序每次都是固定的,并且按照table+entry链表的顺序,而不是插入顺序。

LinkedHashMap用额外的链表保证插入顺序

 

  void createEntry(int hash, K key, V value, int bucketIndex) {

HashMap.Entry
old = table[bucketIndex]; Entry
e = new Entry<>(hash, key, value, old); table[bucketIndex] = e; e.addBefore(header);//插到链表中 size++; }
 

 

Entry
nextEntry() {//遍历链表 if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (nextEntry == header) throw new NoSuchElementException(); Entry
e = lastReturned = nextEntry; nextEntry = e.after; return e; }
 

 

转载地址:http://umdmi.baihongyu.com/

你可能感兴趣的文章
Oracle Linux 6.1 + Oracle 11.2.0.1 RAC + RAW 安装文档
查看>>
Oracle 11g 新特性 -- Online Patching (Hot Patching 热补丁)说明
查看>>
Oracle 11g 新特性 -- ASM 增强 说明
查看>>
Oracle 11g 新特性 -- Database Replay (重演) 说明
查看>>
Oracle 11g 新特性 -- 自动诊断资料档案库(ADR) 说明
查看>>
Oracle 11g 新特性 -- RMAN Data Recovery Advisor(DRA) 说明
查看>>
CSDN博客之星 投票说明
查看>>
Oracle wallet 配置 说明
查看>>
Oracle smon_scn_time 表 说明
查看>>
VBox fdisk 不显示 添加的硬盘 解决方法
查看>>
Secure CRT 自动记录日志 配置 小记
查看>>
RMAN RAC 到 单实例 duplicate 自动分配通道 触发 ORA-19505 错误
查看>>
mysql 随机分页的优化
查看>>
DB2快速创建测试库
查看>>
利用db2look查看ddl
查看>>
java中的mmap实现
查看>>
Redis的Aof被阻塞原因调查
查看>>
Redis Cluster的FailOver失败案例分析
查看>>
Android Alarm驱动源代码分析(Alarm.c)
查看>>
S3C2440上LCD驱动 (FrameBuffer)实例开发讲解
查看>>