java:S2175 Using Number as key type in a Map produces false-positives when int is used when accessing the map value

When defining a Map with “Number” as key type parameter, sonar-java raises an Issue, when the map is access with the primitive integer value. This is a false-positive, as due to auto-boxing, the access is correct and produces no errors.

Used Versions

  • SonarQube: 8.1.0.31237
  • SonarJava: 6.3 (build 21585)

Code Sample

1  import java.util.HashMap;
2  import java.util.Map;
3  
4  public class SonarS2175Test
5  {
6     private Map<Number, String> testMap = new HashMap<>();
7  
8     public SonarS2175Test()
9     {
10       testMap.put(Integer.valueOf(1), "one");
11       testMap.put(Integer.valueOf(2), "two");
12       testMap.put(Integer.valueOf(3), "three");
13    }
14 
15    public String getString(int number)
16    {
17       if (testMap.containsKey(number))
18       {
19          return testMap.get(number);
20       }
21       return "";
22    }
23 
24 }

When analysing this code with SonarQube, two issues are raised:
Line 17: A “Map<Number, String>” cannot contain a “int” in a “Number” type.
Line 19: A “Map<Number, String>” cannot contain a “int” in a “Number” type.

In my opinion, these issues are false-positives. Taking auto-boxing into consideration, there shouldn’t be an issue.

1 Like

Hello @tschindler

Thanks for the feedback and the crystal clear description of the problem, it is an example of what a bug report should look like. :slight_smile:

Ticket created: SONARJAVA-3540.

Best,
Quentin

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.