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

Inappropriate "Collection" calls should not be made

    XMLWordPrintable

    Details

    • Type: Bug Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      A "[class]<[type]>" cannot contain a "[ytype]".
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      15min
    • Analysis Scope:
      Main Sources, Test Sources
    • CERT:
      EXP04-J.
    • FindBugs:
      GC_UNCHECKED_TYPE_IN_GENERIC_CALL, GC_UNRELATED_TYPES

      Description

      The java.util.Collection API has methods that accept Object parameters such as Collection.remove(Object o), and Collection.contains(Object o). When the actual type of the object provided to these methods is not consistent with the type declared on the Collection instantiation, those methods will always return false or null. This is most likely unintended and hides a design problem.

      This rule raises an issue when the type of the argument of the following APIs is unrelated to the type used for the Collection declaration:

      • Collection.remove(Object o)
      • Collection.removeAll(Collection<?>)
      • Collection.contains(Object o)
      • List.indexOf(Object o)
      • List.lastIndexOf(Object o)
      • Map.containsKey(Object key)
      • Map.containsValue(Object value)
      • Map.get(Object key)
      • Map.getOrDefault(Object key, V defaultValue)
      • Map.remove(Object key)
      • Map.remove(Object key, Object value)

      Noncompliant Code Example

      public class S2175 {
      
        public static void main(String[] args) {
          String foo = "42";
          Map<Integer, Object> map = new HashMap<>();
          map.remove(foo); // Noncompliant; will return 'null' for sure because 'map' is handling only Integer keys
      
          // ...
          
          List<String> list = new ArrayList<String>();
          Integer integer = Integer.valueOf(1);
          if (list.contains(integer)) { // Noncompliant; always false.
            list.remove(integer); // Noncompliant; list.add(integer) doesn't compile, so this will always return 'false'
          }
        }
      
      }
      

      See

      • CERT, EXP04-J. - Do not pass arguments to certain Java Collections Framework methods that are a different type than the collection parameter type

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              ann.campbell.2 Ann Campbell
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

                Dates

                Created:
                Updated: