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


