All Downloads are FREE. Search and download functionalities are using the official Maven repository.

resources.report.rules.pmd.UseArraysAsList.html Maven / Gradle / Ivy

Go to download

Sanity4J was created to simplify running multiple static code analysis tools on the Java projects. It provides a single entry point to run all the selected tools and produce a consolidated report, which presents all findings in an easily accessible manner.

The newest version!


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
     }
  }
}
   




© 2015 - 2024 Weber Informatics LLC | Privacy Policy