Inspectopedia Help

'for' loop can be replaced with enhanced for loop

Reports for loops that iterate over collections or arrays, and can be automatically replaced with an enhanced for loop (foreach iteration syntax).

Example:

for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) { String item = iterator.next(); System.out.println(item); }

After the quick-fix is applied:

for (String item : list) { System.out.println(item); }

Use the Report indexed 'java.util.List' loops option to find loops involving list.get(index) calls. Generally, these loops can be replaced with enhanced for loops, unless they modify an underlying list in the process, for example, by calling list.remove(index). If the latter is the case, the enhanced for loop may throw ConcurrentModificationException. Also, in some cases, list.get(index) loops may work a little bit faster.

Use the Do not report iterations over untyped collections option to ignore collections without type parameters. This prevents the creation of enhanced for loop variables of the java.lang.Object type and the insertion of casts where the loop variable is used.

This inspection only reports if the language level of the project or module is 5 or higher.

Inspection options

Option

Type

Default

Report indexed 'java.util.List' loops

Checkbox

true

Do not report iterations over untyped collections

Checkbox

false

Inspection Details

Available in:

IntelliJ IDEA 2023.3, Qodana for JVM 2023.3

Plugin:

Java, 233.SNAPSHOT

Last modified: 13 July 2023