// Using entrySet() to get the entry's of the map
// m is previously created Map.
Set<Map.Entry<String,Integer>> s = m.entrySet();
for (Map.Entry<String, Integer> it: s)
{
String str = it.getKey();
}Map.Enty只是一个接口。
接口没有getKey();方法的实现
为什么上面的代码可以工作?就像编译器如何知道getKey()的行为一样
发布于 2018-05-11 09:44:58
如下所示的代码:
static class Entry<K,V> implements Map.Entry<K,V>这段代码来自HashMap,如果我们放入一个新的K-V条目,HashMap将创建一个新的HashMap.Entry实例:
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}因此,for-each循环中的每个it变量都是HashMap.Entry 类的一个实例,该类实现了Map.Entry 接口。
https://stackoverflow.com/questions/50283782
复制相似问题