Skip to content

[java] AvoidReassigningLoopVariables detects some harmless reassigning of loop variables in foreach #2595

@wuchiuwong

Description

@wuchiuwong

Affects PMD Version:
6.22.0

Rule:
AvoidReassigningLoopVariables

Description:
AvoidReassigningLoopVariables detects some harmless reassigning of loop variables in foreach.
In some cases, modifying the loop variable of foreach is to further process the variable. This is a commonly used writting and does not cause problems.
It is recommended to adjust the detection content of the rule to reduce unimportant error warnings.

Code Sample demonstrating the issue:
Example 1

for (String item : items) {
	item = item.trim();
	httpMethods = httpMethods | HttpMethods.getMethod(item);
}

Example 2

for (String g : globalChange) {
	g = g.substring(0,g.lastIndexOf(":"));
	g = g + ": 1;";
	FileUtil.writeLineToFile(w, g);
}

Example 3

for (String message : messages) {
	message = OutputFormatter.escape(message);
	lines.add(String.format(large ? "  %s  " : " %s ", message));
	len = Math.max(length(message) + (large ? 4 : 2), len);
}

Expected outcome:
false-positive

Running PMD through:
CLI

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions