是否可以在不创建新对象的情况下迭代 ConcurrentHashMap?

Is it possible to iterate a ConcurrentHashMap without creating new objects?

分析我的 android 游戏后,我注意到在我在整个主游戏循环中调用的简单迭代过程中生成了异常数量的 ConcurrentHashmap。代码如下

    public void checkIfStillNeedsToShowUI() {

      for (Map.Entry<String, GameUI> gameUIEntry : listOfUIObjects.entrySet()) {
        if(!gameUIEntry.getValue().isShowing()){//ignore what not showing
            continue;
        }
        final GameUI tmpGameUI = (gameUIEntry.getValue());
        if(!tmpGameUI.hasReasonForShowing()){
            continue;
        }

        if(tmpGameUI.reasonForShowing.checkReason()){
            tmpGameUI.setShowing(true);
        } else {
            tmpGameUI.setShowing(false);
        }

    }
}

结果如下

这正常吗?还是我做错了什么?我知道使用 generic/enhanced for 循环类型会导致创建一个对象以便访问它,但我目前不知道另一种迭代哈希图的方法会给我想要的结果。

它们不是 ConcurrentHashMap 的实例,它们是 MapEntry 的实例。

如果你的意思是 MapEntry 个实例,答案是 JDK 不会在 ConcurrentHashMap 的迭代期间创建这些对象的新实例,并且当你使用 ConcurrentHashMap 你可以在EntityIterator class里面的next方法中看到ConcurrentHashMap。问题是管理并发性 JDK 存储类型 Node 的对象,并且这些对象不被认为是导出的,如源代码中的文档所述:

Key-value entry. This class is never exported out as a user-mutable Map.Entry (i.e., one supporting setValue; see MapEntry below), but can be used for read-only traversals used in bulk tasks. Subclasses of Node with a negative hash field are special, and contain null keys and values (but are never exported). Otherwise, keys and vals are never null.

所以 EntryIterator class inside ConcurrentHashMap class 将此对象转换为 MapEntry inside next 方法。如果您仅在单线程应用程序中使用地图,则可以改用 HashMap