//map的遍歷方法以下 for (Map.Entry<String,Integer> entry : map.entrySet()) { System.out.println(entry.getKey()+":"+entry.getValue()); }
HashMap#entrySet方法java
//next邏輯以下 final Node<K,V> nextNode() { Node<K,V>[] t; Node<K,V> e = next; if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (e == null) throw new NoSuchElementException(); //HashMap散列圖、Hashtable散列表是按「有利於隨機查找的散列(hash)的順序」。並不是按輸入順序。 if ((next = (current = e).next) == null && (t = table) != null) { do {} while (index < t.length && (next = t[index++]) == null); } return e; }
LinkedHashMap 重寫了entrySet方法node
public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es; return (es = entrySet) == null ? (entrySet = new LinkedEntrySet()) : es; } //next 邏輯,能夠發現是按node的next指針進行遍歷的 final LinkedHashMap.Entry<K,V> nextNode() { LinkedHashMap.Entry<K,V> e = next; if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (e == null) throw new NoSuchElementException(); current = e; next = e.after; return e; }