# Replace For-Loop with Enhanced-For-Loop
# Description
Since Java 1.5 enhanced for-loops can be used to iterate over collections. This rule replaces old for-loops utilizing iterators with enhanced for-loops in order to improve readability.
# Benefits
Applying this rule leads to more simplicity in the code base by using new language constructs.
# Tags
# Code Changes
Pre
public String testConvertIteratorToForEach(String input) {
List<String> foo = generateList(input);
StringBuilder sb = new StringBuilder();
for (Iterator<String> iterator = foo.iterator(); iterator.hasNext();) {
String s = iterator.next();
sb.append(s);
}
return sb.toString();
}
Post
public String testConvertIteratorToForEach(String input) {
List<String> foo = generateList(input);
StringBuilder sb = new StringBuilder();
for (String s : foo) {
sb.append(s);
}
return sb.toString();
}
# Limitations
Loops where the body modifies the iterator in some way will not be transformed.
Use a Java Refactoring Tool
Automate this Refactoring system-wide
You can apply this refactoring for free with the jSparrow Eclipse IDE plug-in.
Install the plug-in for Eclipse IDE: Eclipse Marketplace.
# Properties
Property | Value |
---|---|
Rule ID | ForToForEach |
First seen in jSparrow version | 1.0.0 |
Minimum Java version | 5 |
Remediation cost | 5 min |