HashMap 原始碼分析 -- entrySet()
阿新 • • 發佈:2019-02-08
HashMap extends AbstractMap implements Map
AbstractMap implements Map
AbstractMap已經實現了map裡的一些公共的介面,比如
size(),isEmpty() 等。在AbstractMap裡留下了一個abstract 方法
public abstract Set<Entry<K,V>> entrySet()
HashMap 實現只是簡單的new EntrySet
public Set<Map.Entry<K,V>> entrySet() {
Set <Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
HashMap的成員類-EntrySet
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public final int size(){ return size; }
public final void clear() { HashMap.this .clear(); }
//建構函式裡new EntryIterator()
public final Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
...
}
HashMap的又一個成員類-EntryIterator extends HashIterator
final class EntryIterator extends HashIterator
implements Iterator <Map.Entry<K,V>> {
public final Map.Entry<K,V> next() {
return nextNode();
}
}
HashMap裡定義的abstract class HashIterator
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;
//table 是HashMap裡的陣列容器,很關鍵的一步
//transient Node<K,V>[] table;
Node<K,V>[] t = table;
current = next = null;
index = 0;
if (t != null && size > 0) {
//直到table[index]不為空,將 table[index]付給next
//也就是next是Node<K,V>
//Node<K,V> implements Map.Entry<K,V>
//因此下面的Iterator<Map.Entry<String,String>>裡的
//泛型是Map.Entry<String,String>
do {} while
(index < t.length && (next = t[index++]) == null);
}
}
....
}
呼叫map的entrySet()來遍歷
Map<String, String> map = new HashMap<String, String>();
map.put("1", "1");
map.put("2", "2");
map.put("3", "3");
Set<Map.Entry<String, String>> mapSet = map.entrySet();
Iterator<Map.Entry<String,String>> it = mapSet.iterator();
while(it.hasNext()){
Map.Entry<String,String> entry = it.next();
System.out.println(entry.getKey() + " = " +entry.getValue());
}