Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-5329

Collection constructors should not be used as java.util.function.Function

    XMLWordPrintable

    Details

    • Type: Bug Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
      None
    • Message:
      Replace this constructor reference with a lambda returning a new {{List/HashMap/...}}.
    • Highlighting:
      Hide

      The constructor reference.

      Show
      The constructor reference.
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Targeted languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      It is very common to pass a collection constructor reference as an argument, for example Collectors.toCollection(ArrayList::new) takes the ArrayList::new constructor. When the method expects a java.util.function.Supplier it is perfectly fine. However when the me argument type is java.util.function.Function it means that an argument will be passed to the constructor.

      The first argument of Collections constructors is usually an integer representing its "initial capacity". This is generally not what the developer expects, but the memory allocation is not visible at first glance.

      This rule raises an issue when a collection constructor is passed by reference as a java.util.function.Function argument.

      Noncompliant Code Example

      Arrays.asList(1, 2, 54000).stream().collect(Collectors.toMap(Function.identity(), ArrayList::new));
      

      Compliant Solution

      Arrays.asList(1, 2, 54000).stream().collect(Collectors.toMap(Function.identity(), id -> new ArrayList<>()));
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              nicolas.harraudeau Nicolas Harraudeau (Inactive)
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: