Java HashMap.entrySet遍历

2018-04-21  本文已影响0人  yuruihua

HashMap通过get方法只能得到value,如何遍历HashMap,访问所有的key和value
transient Set<Map.Entry<K,V>> entrySet;
entrySet是一个set,内部数据是Map.Entry<K,V>,即是HashMap中key-value
1、获取到entrySet
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
2、EntrySet是HashMap内部类
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
public final boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Node<K,V> candidate = getNode(hash(key), key);
return candidate != null && candidate.equals(e);
}
public final boolean remove(Object o) {
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Object value = e.getValue();
return removeNode(hash(key), key, value, true, true) != null;
}
return false;
}
public final Spliterator<Map.Entry<K,V>> spliterator() {
return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
// Android-changed: Detect changes to modCount early.
for (int i = 0; (i < tab.length && modCount == mc); ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
由EntrySet的方法可以看到,可以直接操作table数组,清空,删除等
3、iterator方法
public final Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
返回一个创建的EntryIterator对象
final class EntryIterator extends HashIterator
implements Iterator<Map.Entry<K,V>> {
public final Map.Entry<K,V> next() { return nextNode(); }
}
next的实现是:首先顺序遍历链表,当链表结束收,index++,遍历table数组中下一个链表,一直到遍历结束。
abstract class HashIterator是一个抽象类,内部提供了hasNext,nextNode方法,可以通过iterator.next()获取下一个节点Node,通过iterator遍历HashMap,entrySet支持foreach方法。

上一篇下一篇

猜你喜欢

热点阅读