Skip to content

[java] AvoidArrayLoops regression: from false negative to false positive with final variables #4183

@Androbin

Description

@Androbin

Affects PMD Version: 6.51.0

Rule: AvoidArrayLoops

Description:
While fixing #3847, a regression was introduced in #4159 @adangel, now instead of a false negative we have a false positive.
A final variable may only be ignored if it's computed before the loop (or otherwise constant over the loop).

Code Sample demonstrating the issue:

public class Test {
  public static void sample() {
    final int[] a = new int[10];
    final int[] b = new int[10];
    for (int i=0; i<10; i++) {
      final int c = i;
      b[i] = a[i+c];
    }
  }
}

Expected outcome:

PMD reports a violation at line 5, but that's wrong. That's a false positive.

Running PMD through: CLI

True positive code samples
public class Test {
  public static void sample() {
    final int[] a = new int[10];
    final int[] b = new int[10];
    final int c = 6;
    for (int i=0; i<10; i++) {
      b[i] = a[i+c];
    }
  }
}
public class Test {
  public static void sample() {
    final int[] a = new int[10];
    final int[] b = new int[10];
    for (int i=0; i<10; i++) {
      final int c = 6;
      b[i] = a[i+c];
    }
  }
}
True negative code samples
public class Test {
  public static void sample() {
    final int[] a = new int[10];
    final int[] b = new int[10];
    for (int i=0; i<10; i++) {
      int c = i;
      b[i] = a[i+c];
    }
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematic

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions