HashMap 的 entrySet 生成过程

XuanrenLu XuanrenLu 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
原来以为entrySet是随着put操作一块更新的,后来发现是调用entrySet()方法时才生成,但是在调试的时候,竟然没发现生成entrySet的代码,求解。
下面是证明的代码,不直是否有问题。
public static void main(String[] args){
Map<String, String> map = new HashMap<>();
map.put("1", "one");
Set<Map.Entry<String, String>> entries = null;
try {
Field field = map.getClass().getDeclaredField("entrySet");
field.setAccessible(true);
entries = (Set<Map.Entry<String, String>>)field.get(map);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
System.out.println(entries); // null
System.out.println(map.entrySet()); // [1=one]
}

这是源码,跟到这,发现找不到生成entrySet的代码
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
XuanrenLu
Java SE 62,621 成员 307,251 内容