java - Iterator.hasNext 和 for-each 循环之间有什么关系吗

标签 java list foreach iterator jprofiler

我使用 JProfiler 来分析我的应用程序,因为它是一个巨大的应用程序,所以我非常了解它的性能和效率。
花费的时间太长,所以我将所有 Iterator.hasNext 替换为 for-each 但是当我在 JProfilers CPU View 中看到时,它显示给我 Iterator.hasNext 方法在我使用 for-each 的地方调用。
为什么会这样?这两者之间有什么关系吗? 这是示例代码:

    List<Map<String, Object>> mapList = jdbcTemplate
                        .queryForList(MAP.SELECT_ALL);
                for (Map<String, Object> map : mapList) {
            list.add(fillPreferenceMaster(preferenceMasterMap));
}

最佳答案

是的,增强的 for 语句使用 Iterator 来隐藏可迭代集合,参见 Section 14.14.2 of the JLS :

If the type of Expression is a subtype of Iterable, then let I be the type of the expression Expression.iterator(). The enhanced for statement is equivalent to a basic for statement of the form:

for (I #i = Expression.iterator(); #i.hasNext(); ) {
        VariableModifiersopt Type Identifier = #i.next();
   Statement
}

Where #i is a compiler-generated identifier that is distinct from any other identifiers (compiler-generated or otherwise) that are in scope (§6.3) at the point where the enhanced for statement occurs.

关于java - Iterator.hasNext 和 for-each 循环之间有什么关系吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9356790/

相关文章:

python - 如何从 Python 的 for 循环中的列表中获取某些值?

php - Laravel foreach in 方法仅返回最后一个结果

java - 多页 Tiff 压缩

java - htmlcleaner 只抓取第一个 body 标签和子节点

python - 使用要排除的索引列表进行索引

c# - 为什么 foreach 找不到我的 GetEnumerator 扩展方法?

php - 在 PHP 中将 JSON 数组导出为 CSV

java - 动态更新时 JPanel 出现不需要的重画

java - J2ME 中锁定图形对象

python - 如何在 Python 中重置列表迭代器?