温馨提示×

WeakHashMap如何遍历

小樊
96
2024-07-02 22:08:14
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在遍历WeakHashMap时,通常可以使用迭代器(Iterator)或者forEach方法来实现。以下是使用迭代器遍历WeakHashMap的示例代码:

WeakHashMap<String, Integer> map = new WeakHashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, Integer> entry = iterator.next();
    System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

另外,还可以使用forEach方法来遍历WeakHashMap:

WeakHashMap<String, Integer> map = new WeakHashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

map.forEach((key, value) -> {
    System.out.println("Key: " + key + ", Value: " + value);
});

无论是使用迭代器还是forEach方法,都可以很方便地遍历WeakHashMap并输出其中的键值对。需要注意的是,WeakHashMap中的键值对可能会在GC时被回收,因此在遍历过程中要注意可能会出现空键或值的情况。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:如何正确使用WeakHashMap

0