diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/ForLoopCanBeForeachRule.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/ForLoopCanBeForeachRule.java index 66bd8cbbb5..b8247c86ea 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/ForLoopCanBeForeachRule.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/bestpractices/ForLoopCanBeForeachRule.java @@ -16,6 +16,7 @@ import net.sourceforge.pmd.lang.java.ast.ASTExpression; import net.sourceforge.pmd.lang.java.ast.ASTForInit; import net.sourceforge.pmd.lang.java.ast.ASTForStatement; import net.sourceforge.pmd.lang.java.ast.ASTForUpdate; +import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration; import net.sourceforge.pmd.lang.java.ast.ASTName; import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix; import net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix; @@ -102,12 +103,17 @@ public class ForLoopCanBeForeachRule extends AbstractJavaRule { } - /* Finds the declaration of the index variable and its occurrences */ + /* Finds the declaration of the index variable and its occurrences, null to abort */ private Entry> getIndexVarDeclaration(ASTForInit init, ASTForUpdate update) { if (init == null) { return guessIndexVarFromUpdate(update); } + int numDeclaredVars = init.getFirstChildOfType(ASTLocalVariableDeclaration.class).findChildrenOfType(ASTVariableDeclarator.class).size(); + if (numDeclaredVars > 1) { + return null; // will abort in the calling function + } + Map> decls = init.getScope().getDeclarations(VariableNameDeclaration.class); Entry> indexVarAndOccurrences = null; diff --git a/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/rule/bestpractices/xml/ForLoopCanBeForeach.xml b/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/rule/bestpractices/xml/ForLoopCanBeForeach.xml index 6e8778e8bf..881b2b5a6e 100644 --- a/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/rule/bestpractices/xml/ForLoopCanBeForeach.xml +++ b/pmd-java/src/test/resources/net/sourceforge/pmd/lang/java/rule/bestpractices/xml/ForLoopCanBeForeach.xml @@ -287,4 +287,25 @@ } ]]> + + + Iterating on multiple iterators should whitelist the loop, refs #784 + + 0 + it; + Iterable other; + for (Iterator iterator = it.iterator(), otherIterator = other.iterator(); iterator.hasNext();) { + E item = iterator.next(); + E otherItem = otherIterator.next(); + doStuff(); + } + } + } + ]]> + + +