java:S1640 false negative when key is null

Product: SonarQube Community (self-hosted)
sonar-java version: sonar-java 8.28.0.43176 on SonarQube Community Build 26.4.0.121862
Java source level: 21 (javac 21, source/target 17)

Rule

java:S1640 — “Maps with keys that are enum values should be replaced with EnumMaps”

Description

S1640 behaves inconsistently when a null argument in Map<COLOR, String>.put(...) is written as plain null versus (COLOR) null.

Reproducer

import java.util.HashMap;
import java.util.Map;

public class MyClass {
    public enum COLOR { RED, GREEN, BLUE, ORANGE; }

    // BEFORE — S1640 NOT reported
    public void mapMoodA() {
        Map<COLOR, String> moodMap = new HashMap<COLOR, String>();
        moodMap.put(null, "null");
        moodMap.put(COLOR.BLUE, "blue");
    }

    // AFTER — S1640 reported ("Convert this Map to an EnumMap.")
    public void mapMoodB() {
        Map<COLOR, String> moodMap = new HashMap<COLOR, String>();
        moodMap.put((COLOR) null, "null");
        moodMap.put(COLOR.BLUE, "blue");
    }
}

Hi @Emilyaxe ,

Thanks for the report and the clear reproducer.

I’ve looked into this, and since EnumMap does not permit null keys (throwing a NullPointerException), recommending a migration when a null key is explicitly used would actually lead to broken code.

In this context, your “Case B” is likely a False Positive rather than “Case A” being a False Negative. I will create a ticket to ensure the rule ignores maps where null is used as a key to avoid proposing unsafe remediations.

Best regards,

Romain