1.遍历例子
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapTraversalExample {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);
// 获取HashMap的迭代器
Iterator<Map.Entry<String, Integer>> iterator = hashMap.entrySet().iterator();
// 遍历HashMap
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
2.遍历相关源码
2.1.entrySet
获取全局变量entrySet,如果为null,新建一个EntrySet
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
transient Set<Map.Entry<K,V>> entrySet;
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
//如果为null, 则创建一个new EntrySet()
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
}
2.2.iterator()
创建EntryIterator,构造方法里会给next赋值
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
abstract class HashIterator {
Node<K,V> next; // next entry to return
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);
}
}
}
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public final Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
}
}
2.3.hasNext
判断next是否为null
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
final class EntryIterator extends HashIterator{
public final boolean hasNext() {
return next != null;
}
}
}
2.4.next
将这次要返回的节点赋值给e;
更新next
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
final class EntryIterator extends HashIterator implements Iterator<Map.Entry<K,V>> {
public final Map.Entry<K,V> next() {
return nextNode();
}
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();
}
//先看e.next是否为null,为null说明到了尾;需要找下一个桶不为null
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);
}
return e;
}
}
}