Merge pull request #3900 from adangel:issue-3867-usearraysaslist

[java] Fix UseArraysAsList with method calls #3900
This commit is contained in:
Andreas Dangel
2022-04-28 14:51:31 +02:00
3 changed files with 34 additions and 4 deletions

View File

@ -998,6 +998,8 @@ You must use `new ArrayList<>(Arrays.asList(...))` if that is inconvenient for y
PrimaryPrefix/Name/@Image = ancestor::MethodDeclaration[1]//FormalParameter/VariableDeclaratorId[@ArrayType=true()]/@Name
and PrimarySuffix/Expression/PrimaryExpression/PrimaryPrefix/Name
]
(: ignore method calls :)
[not(PrimarySuffix/Arguments)]
]
]
]]>
@ -1009,12 +1011,14 @@ You must use `new ArrayList<>(Arrays.asList(...))` if that is inconvenient for y
public class Test {
public void foo(Integer[] ints) {
// could just use Arrays.asList(ints)
List<Integer> l= new ArrayList<>(100);
for (int i=0; i< 100; i++) {
List<Integer> l = new ArrayList<>(100);
for (int i = 0; i < 100; i++) {
l.add(ints[i]);
}
for (int i=0; i< 100; i++) {
l.add(a[i].toString()); // won't trigger the rule
List<Integer> anotherList = new ArrayList<>();
for (int i = 0; i < 100; i++) {
anotherList.add(ints[i].toString()); // won't trigger the rule
}
}
}

View File

@ -163,6 +163,30 @@ public class UseArraysAsListFN {
}
return result;
}
}
]]></code>
</test-code>
<test-code>
<description>[java] UseArraysAsList with method call #3867</description>
<expected-problems>1</expected-problems>
<expected-linenumbers>9</expected-linenumbers>
<code><![CDATA[
import java.util.ArrayList;
import java.util.List;
public class Test {
public void foo(Integer[] ints) {
// could just use Arrays.asList(ints)
List<Integer> l = new ArrayList<>(100);
for (int i = 0; i < 100; i++) {
l.add(ints[i]); // line 9, here is the violation
}
List<Integer> anotherList = new ArrayList<>();
for (int i = 0; i < 100; i++) {
anotherList.add(ints[i].toString()); // line 13 - false positive
}
}
}
]]></code>
</test-code>