resources.report.rules.pmd.UseArraysAsList.html Maven / Gradle / Ivy
UseArraysAsList
UseArraysAsList
The java.util.Arrays class has a “asList” method that should be used when you want to create a new List from an array of objects. It is faster than executing a loop to copy all the elements of the array one by one.
//Statement[
(ForStatement) and (ForStatement//VariableInitializer//Literal[@IntLiteral='true' and @Image='0']) and (count(.//IfStatement)=0)
]
//StatementExpression[
PrimaryExpression/PrimaryPrefix/Name[
substring-before(@Image,'.add') = ancestor::MethodDeclaration//LocalVariableDeclaration[
./Type//ClassOrInterfaceType[
@Image = 'Collection' or
@Image = 'List' or @Image='ArrayList'
]
]
/VariableDeclarator/VariableDeclaratorId[
count(..//AllocationExpression/ClassOrInterfaceType[
@Image="ArrayList"
]
)=1
]/@Image
]
and
PrimaryExpression/PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix/Name
[
@Image = ancestor::MethodDeclaration//LocalVariableDeclaration[@Array="true"]/VariableDeclarator/VariableDeclaratorId/@Image
or
@Image = ancestor::MethodDeclaration//FormalParameter/VariableDeclaratorId/@Image
]
/../..[count(.//PrimarySuffix)
=1]/PrimarySuffix/Expression/PrimaryExpression/PrimaryPrefix
/Name
]
Example(s):
public class Test {
public void foo(Integer[] ints) {
// could just use Arrays.asList(ints)
List l= new ArrayList(10);
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
}
}
}