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.

There is a newer version: 1.1.1
Show newest version


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 - 2024 Weber Informatics LLC | Privacy Policy