Ok, so this is something you'd almost/arguably never see in good code, but... I did have a case where it came up for more or less valid reasons, and aside from whether it could be avoided with some best practices about variables and code structure it's not part of the repetition of a loop and therefore shouldn't be flagged by the rule java-optimizations/AvoidInstantiatingObjectsInLoops:
import java.util.ArrayList;
import java.io.File;
public class TestInstantiationInLoop {
public static void main(String args[]) {
for (String test : new ArrayList<String>()) { // facetious but simple example
System.out.println(test);
}
for (String filename : new File("subdirectory").list()) { // complex but realistically conceivable (albeit exagerrated/oversimplified/rarely advisable) example
System.out.println(filename);
}
}
}
The following should produce nothing, but reports both of the above loops:
pmd -d TestInstantiationInLoop.java -R java-optimizations/AvoidInstantiatingObjectsInLoops
This will be fixed with the next release.