Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package checks;

import com.google.common.collect.Maps;
import java.util.Map;

class IdentityHashMapBoxedKeyCheckGuavaSample {

void boxedKeys() {
Map<Boolean, String> booleans = Maps.newIdentityHashMap(); // Noncompliant {{Use a map that compares keys by value because IdentityHashMap compares keys by reference.}}
// ^^^^^^^^^^^^^^^^^^^^^^^^^
Map<Byte, String> bytes = Maps.newIdentityHashMap(); // Noncompliant
Map<Character, String> characters = Maps.newIdentityHashMap(); // Noncompliant
Map<Short, String> shorts = Maps.newIdentityHashMap(); // Noncompliant
Map<Integer, String> integers = Maps.newIdentityHashMap(); // Noncompliant
Map<Long, String> longs = Maps.newIdentityHashMap(); // Noncompliant
Map<Float, String> floats = Maps.newIdentityHashMap(); // Noncompliant
Map<Double, String> doubles = Maps.newIdentityHashMap(); // Noncompliant
}

void compliant() {
Map<String, Boolean> boxedValue = Maps.newIdentityHashMap();
Map<String, String> strings = Maps.newIdentityHashMap();
Map<Object, String> objects = Maps.newIdentityHashMap();
}

<T> void genericKey() {
Map<T, String> generic = Maps.newIdentityHashMap();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package checks;

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

class IdentityHashMapBoxedKeyCheckSample {

void boxedKeys(Map<Integer, String> source) {
Map<Boolean, String> booleans = new IdentityHashMap<>(); // Noncompliant
Map<Byte, String> bytes = new IdentityHashMap<>(); // Noncompliant
Map<Character, String> characters = new IdentityHashMap<>(); // Noncompliant
Map<Short, String> shorts = new IdentityHashMap<>(); // Noncompliant
Map<Integer, String> integers = new IdentityHashMap<>(); // Noncompliant
Map<Long, String> longs = new IdentityHashMap<>(); // Noncompliant
Map<Float, String> floats = new IdentityHashMap<>(); // Noncompliant
Map<Double, String> doubles = new IdentityHashMap<>(); // Noncompliant
Map<Integer, String> explicit = new IdentityHashMap<Integer, String>(); // Noncompliant
Map<Integer, String> copied = new IdentityHashMap<>(source); // Noncompliant
var inferred = new IdentityHashMap<Integer, String>(); // Noncompliant {{Use a map that compares keys by value because IdentityHashMap compares keys by reference.}}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}

void compliant() {
Map<String, Boolean> boxedValue = new IdentityHashMap<>();
Map<String, String> strings = new IdentityHashMap<>();
Map<Object, String> objects = new IdentityHashMap<>();
Map<Integer, String> hashMap = new HashMap<>();
IdentityHashMap raw = new IdentityHashMap();
}

<T> void genericKey() {
Map<T, String> generic = new IdentityHashMap<>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.checks;

import java.util.List;
import java.util.Set;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.semantic.MethodMatchers;
import org.sonar.plugins.java.api.semantic.Type;
import org.sonar.plugins.java.api.tree.ExpressionTree;
import org.sonar.plugins.java.api.tree.MethodInvocationTree;
import org.sonar.plugins.java.api.tree.Tree;

@Rule(key = "S9401")
public class IdentityHashMapBoxedKeyCheck extends IssuableSubscriptionVisitor {

private static final String IDENTITY_HASH_MAP = "java.util.IdentityHashMap";
private static final String MESSAGE = "Use a map that compares keys by value because IdentityHashMap compares keys by reference.";
private static final Set<String> BOXED_TYPES = Set.of(
"java.lang.Boolean",
"java.lang.Byte",
"java.lang.Character",
"java.lang.Short",
"java.lang.Integer",
"java.lang.Long",
"java.lang.Float",
"java.lang.Double");
private static final MethodMatchers GUAVA_IDENTITY_HASH_MAP_FACTORY = MethodMatchers.create()
.ofTypes("com.google.common.collect.Maps")
.names("newIdentityHashMap")
.addWithoutParametersMatcher()
.build();

@Override
public List<Tree.Kind> nodesToVisit() {
return List.of(Tree.Kind.NEW_CLASS, Tree.Kind.METHOD_INVOCATION);
}

@Override
public void visitNode(Tree tree) {
ExpressionTree expression = (ExpressionTree) tree;
if (isIdentityHashMapCreation(tree, expression.symbolType()) && hasBoxedKey(expression.symbolType())) {
reportIssue(tree, MESSAGE);
}
}

private static boolean isIdentityHashMapCreation(Tree tree, Type resultType) {
return tree.is(Tree.Kind.NEW_CLASS)
? resultType.is(IDENTITY_HASH_MAP)
: GUAVA_IDENTITY_HASH_MAP_FACTORY.matches((MethodInvocationTree) tree);
}

private static boolean hasBoxedKey(Type resultType) {
List<Type> typeArguments = resultType.typeArguments();
return typeArguments.size() == 2 && BOXED_TYPES.contains(typeArguments.get(0).fullyQualifiedName());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.checks;

import org.junit.jupiter.api.Test;
import org.sonar.java.checks.verifier.CheckVerifier;

import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath;

class IdentityHashMapBoxedKeyCheckTest {

@Test
void test() {
CheckVerifier.newVerifier()
.onFile(mainCodeSourcesPath("checks/IdentityHashMapBoxedKeyCheckSample.java"))
.withCheck(new IdentityHashMapBoxedKeyCheck())
.verifyIssues();
}

@Test
void test_without_semantic() {
CheckVerifier.newVerifier()
.onFile(mainCodeSourcesPath("checks/IdentityHashMapBoxedKeyCheckSample.java"))
.withCheck(new IdentityHashMapBoxedKeyCheck())
.withoutSemantic()
.verifyIssues();
}

@Test
void test_guava() {
CheckVerifier.newVerifier()
.onFile(mainCodeSourcesPath("checks/IdentityHashMapBoxedKeyCheckGuavaSample.java"))
.withCheck(new IdentityHashMapBoxedKeyCheck())
.verifyIssues();
}

@Test
void test_guava_without_semantic() {
CheckVerifier.newVerifier()
.onFile(mainCodeSourcesPath("checks/IdentityHashMapBoxedKeyCheckGuavaSample.java"))
.withCheck(new IdentityHashMapBoxedKeyCheck())
.withoutSemantic()
.verifyNoIssues();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<p>This rule raises an issue when an <code>IdentityHashMap</code> is created with a boxed primitive type as its key type.</p>
<h2>Why is this an issue?</h2>
<p><code>IdentityHashMap</code> compares keys by reference instead of calling <code>equals()</code>. Boxed primitive types represent values as
objects, but boxing the same primitive value more than once does not always return the same object. For example, some <code>Integer</code> values are
cached while others may be represented by distinct instances.</p>
<p>Consequently, an <code>IdentityHashMap</code> with boxed primitive keys can appear to work for some values and fail for others. A lookup can return
<code>null</code> even when the map contains a key with the same primitive value.</p>
<h2>How to fix it</h2>
<p>Use a map implementation that compares keys by value when the key represents a primitive value. If reference equality is required, use key objects
whose identity is deliberate and stable.</p>
<h3>Code examples</h3>
<h4>Noncompliant code example</h4>
<pre data-diff-id="1" data-diff-type="noncompliant">
Comment thread
nathsou marked this conversation as resolved.
Map&lt;Integer, UserSession&gt; sessions = new IdentityHashMap&lt;&gt;(); // Noncompliant

sessions.put(500, session);
UserSession retrieved = sessions.get(500); // May return null
</pre>
<h4>Compliant solution</h4>
<pre data-diff-id="1" data-diff-type="compliant">
Map&lt;Integer, UserSession&gt; sessions = new HashMap&lt;&gt;();

sessions.put(500, session);
UserSession retrieved = sessions.get(500);
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
<li>Java Documentation - <a
href="https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/IdentityHashMap.html"><code>IdentityHashMap</code> class</a></li>
<li>Java Documentation - <a
href="https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Integer.html#valueOf(int)"><code>Integer.valueOf(int)</code>
method</a></li>
</ul>
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"title": "IdentityHashMap keys should not be boxed primitive types",
"type": "BUG",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"suspicious"
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-9401",
"sqKey": "S9401",
"scope": "All",
"quickfix": "infeasible",
"code": {
"impacts": {
"RELIABILITY": "MEDIUM"
},
"attribute": "LOGICAL"
}
}
Empty file.
Loading