
resources.report.rules.pmd.UseArraysAsList.html Maven / Gradle / Ivy
UseArraysAsList
UseArraysAsList
The class java.util.Arrays has a "asList" method that
should be use when you want to create a new List from
an array of objects. It is faster than executing a loop to
cpy all the elements of the array one by one
This rule is defined by the following XPath expression:
//Statement[
(ForStatement) 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]
/../..[count(.//PrimarySuffix)
=1]/PrimarySuffix/Expression/PrimaryExpression/PrimaryPrefix
/Name
]
Example:
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
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy