HashMap为什么是无序?
HashMap的数据结构是table[entry],entry是一个链表结构,数据的每个元素是一个链表。不同key,但是具有相同hashcode会落在table[hashcode]的链表上
当使用iterator遍历时,使用如下code:
final Entry<K,V> nextEntry() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Entry<K,V> 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<K,V> old = table[bucketIndex];
Entry<K,V> e = new Entry<>(hash, key, value, old);
table[bucketIndex] = e;
e.addBefore(header);//插到链表中
size++;
}
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;
}
转载:http://xiaoz5919.iteye.com/blog/1250427
分享到:
相关推荐
HashMap,HashTable,LinkedHashMap,TreeMap的区别
java中HashMap,LinkedHashMap,TreeMap,HashTable的区别
主要介绍了 java HashMap,TreeMap与LinkedHashMap的详解的相关资料,这里提供实例代码,帮助大家学习理解 这部分的内容,需要的朋友可以参考下
HashMap和LinkedHashMap 描述 该项目提供了可在Node.js和浏览器上运行的HashMap和LinkedHashMap类。 它们都是像一样的简化实现 它使用改进的算法生成哈希。 这样可确保在所有铲斗上尽可能广泛地散布。 根据规范,...
HashMap底层实现原理HashMap与HashTable区别HashMap与HashSet区别。HashMap、HashTable和HashSet是Java中常用的数据结构,它们的底层实现原理以及区别如下:HashMap底层实现原理: HashMap基于哈希表(HashTable)...
hashmap与hashtable区别 主要是应用于存值的数值对
HashMap 是无序的,它不保证元素的任何特定顺序。 HashMap 不是线程安全的;多线程环境下,建议使用 ConcurrentHashMap,或者使用 Collections.synchronizedMap(hashMap) 将 HashMap 转成线程同步的。 只能使用...
初级程序员面试经常问道的问题,HashMap与HashTable区别,希望有帮助
主要介绍了HashMap vs TreeMap vs Hashtable vs LinkedHashMap的相关知识,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
涵盖绝大部分HashMap与ConcurrentHashMap的面试题 附带答案
hashmap实例 hashmap实例hashmap实例hashmap实例
HashMap数据结构,HashMap的构造方法,HashMap的put,HashMap的get
hashmap相关的面试题
HashMap介绍和使用
Java8HashMap键与Comparable接口编程开发技术共3页.pdf.zip
HASHMAP排序,对一个无序以KEY为数字的MAP进行排序,比较简单操作
HashMap是一个散列桶(数组和链表),它存储的内容是键值对(key-value)映射HashMap采用了数组和链表的数据结构,能在查询和修改方便继承了数组的线性查找和链表的寻址修改HashMap是非synchronized,所以HashMap很快...
HashMap存放.doc
动态扩容:当HashMap中的元素数量超过了容量(默认为16)与负载因子(默认为0.75)的乘积时,HashMap会自动扩容,即创建一个新的数组,并将原来的元素重新映射到新的数组中。 高性能:由于使用了哈希表,HashMap在查找...
HashTable不支持空键值对! 而HashMap支持空键值对!