Inspectopedia
 
2024.3

'for' loop can be replaced with enhanced for loop

Warning
New
Last modified: 03 December 2024

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

Example:

After the quick-fix is applied:

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 depends on the Java feature 'For-each loops', which is available since Java 5.