WeakHashMap如何遍历

   2024-10-07 4870
核心提示:在遍历WeakHashMap时,通常可以使用迭代器(Iterator)或者forEach方法来实现。以下是使用迭代器遍历WeakHashMap的示例代码:Wea

在遍历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时被回收,因此在遍历过程中要注意可能会出现空键或值的情况。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号