LinkedHashMap和HashMap的区别
LinkedHashMap是HashMap的子类,它和HashMap的区别是,可以按照节点插入的自然顺序(或者节点的操作顺序)来迭代所有节点。而且它的迭代比HashMap更快,因为HashMap遍历的数据结构要复杂一点,而LinkedHashMap用一个双链表来迭代。
HashMap的迭代器
HashMap的三种迭代器都是HashIterator的子类。
final class KeyIterator extends HashIterator
implements Iterator<K> {
public final K next() { return nextNode().key; }
}
final class ValueIterator extends HashIterator
implements Iterator<V> {
public final V next() { return nextNode().value; }
}
final class EntryIterator extends HashIterator
implements Iterator<Map.Entry<K,V>> {
public final Map.Entry<K,V> next() { return nextNode(); }
}
HashIterator抽象类
从源码可知,迭代器访问元素的顺序是从桶位数组第0位开始往后逐个桶位寻找,每个桶中的结构要么是单链表要么是实现了红黑树的双链表,都是链式结构,所以右可以逐个寻找。这也就是HashMap中元素的访问顺序,和hash&table.length
、hash值和Key值都有关系。
abstract class HashIterator {
Node<K,V> next; // next entry to return
Node<K,V> current; // current entry
int expectedModCount; // for fast-fail
int index; // current slot
HashIterator() {
expectedModCount = modCount;
Node<K,V>[] t = table;
current = next = null;
index = 0;
// 初始化next指向第一个节点
if (t != null && size > 0) { // advance to first entry
do {} while (index < t.length && (next = t[index++]) == null);
}
}
public final boolean hasNext() {
return next != null;
}
final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
if (modCount != expectedModCount)
throw new ConcurrentMod