一、DEBUG分析
从图上可以看出当第一次往hashMap里面存值的时候,entrySet也会把hashMap的所有元素的引用地址存储起来,至于是怎么在代码中实现的,查阅了一些资料感觉都没有说到位,自己看源码也没看出结果,所以这部分就暂时跳过,现在可以确定的是我们hashMap里面存值的时候,entrySet也会把引用地址存一份,到时候查询的时候也可以通过entrySet来迭代遍历
Set<Map.Entry<String,String>> set = hashMap.entrySet();
获取一个
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
static class Node<K,V> implements Map.Entry<K,V> {....}
二、使用步骤
public static void main(String[] args) {
HashMap<Stringg,String> hashMap = new HashMap<>(12);
hashMap.put("test1","测试1");
hashMap.put("test2","测试2");
Set<Map.Entry<Object,String>> set = hashMap.entrySet();
for (Map.Entry<Object,String> entry : set) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}