基础使用:
HashMap集合中的entrySet()方法可以得到各个键值对映射关系的集合。
然后在Map.Entry中包含了getKey()和getValue()方法获取键和值。
示例:
public class Demo {
public static void main(String[] args) {
Map map = new HashMap<>();
map.put("abc","123");
map.put("efg", "456");
//使用增强for遍历循环Map集合
Set> entrySet = map.entrySet();
for(Map.Entry entry : entrySet){
System.out.println(entry.getKey()+"->"+entry.getValue());
}
}
}
代码执行原理分析:
HashMap中的entrySet()方法返回Set
public Set> entrySet() { Set > es; return (es = entrySet) == null ? (entrySet = new EntrySet()) : es; }
entrySet方法的方法的原理其实和keySet()方法、values()方法的原理是一样的。
分析entrySet()方法 源码:
public Set> entrySet() { Set > es; return (es = entrySet) == null ? (entrySet = new EntrySet()) : es; }
我们现在看看编译后的字节码文件Demo.class文件:
public class Demo {
public Demo() {
}
public static void main(String[] args) {
Map map = new HashMap();
map.put("abc", "123");
map.put("efg", "456");
Set> entrySet = map.entrySet();
Iterator var3 = entrySet.iterator();
while(var3.hasNext()) {
Entry entry = (Entry)var3.next();
PrintStream var1 = System.out;
String var1 = (String)entry.getKey();
var1.println(var1 + "->" + (String)entry.getValue());
}
}
}
能够获取元素是通过迭代器的遍历得来的,所以entrySet()方法能有键值对的映射集合,是因为有iterator方法。那么我们想一下这个iterator方法是怎么来的呢?是因为entrySet()方法中使用new实例化了一个EntrySet类
我们再查看EntrySet类的源码,里面有个iterator()方法字节码调用的就是这个iterator()方法
在方法的return语句中又实例化了EntryIterator类作为返回值,是一个迭代器,我们现查看EntryIterator类的源码,它只有一个next方法:
final class EntryIterator extends HashIterator
implements Iterator> {
public final Map.Entry next() { return nextNode(); }
}
next()方法被调用返回的类型是Map.Entry
final NodenextNode() { Node [] t; Node e = next; if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (e == null) throw new NoSuchElementException(); if ((next = (current = e).next) == null && (t = table) != null) { do {} while (index < t.length && (next = t[index++]) == null); } return e; }
nextNode()方法作用就是返回下一个节点。
Node类是HashMap的静态内部类:
Entry是Map的内部接口,该Entry接口有几个方法:
interface Entry{ K getKey(); V getValue(); V setValue(V value); boolean equals(Object o); int hashCode();
所以我们可以通过entry.getKey() 和 entry.getValue()方法获取到键和值。
注意:Node



