The interfaces of the Java Collections Framework [JCF 2014] use generically typed, parameterized methods, such as add(E e)
and put(K key, V value)
, to insert objects into the collection or map, but they have other methods, such as contains()
, remove()
, and get()
, that accept an argument of type Object
rather than a parameterized type. Consequently, these methods accept an object of any type. The collections framework interfaces were designed in this manner to maximize backwards compatibility, but this design can also lead to coding errors. Programmers must ensure that arguments passed to methods such as Map<K,V>
get()
, Collection<E>
contains()
, and remove()
have the same type as the parameterized type of the corresponding class instance.
Noncompliant Code Example
After adding and removing 10 elements, the HashSet
in this noncompliant code example still contains 10
elements and not the expected 0. Java's type checking requires that only values of type Short
can be inserted into s. Consequently, the programmer has added a cast to short
so that the code will compile. However, the Collections<E>.remove()
method accepts an argument of type Object
rather than of type E
, allowing a programmer to attempt to remove an object of any type. In this noncompliant code example, the programmer has neglected to also cast the variable i
before passing it to the remove()
method, which is autoboxed into an object of type Integer
rather than one of type Short
. The HashSet
contains only values of type Short
; the code attempts to remove objects of type Integer
. Consequently, the remove()
method has no effect.
Code Block | ||
---|---|---|
| ||
import java.util.HashSet;
|
Wiki Markup |
---|
A boxing conversion converts the value of a primitive type to the corresponding value of the reference type, for example, from {{int}} to {{Integer}} \[[JLS 2005|AA. Bibliography#JLS 05]\]. This is convenient in cases where an object parameter is required, such as with collection classes like {{Map}} and {{List}}. Another use case is for interoperation with methods that require their parameters to be object references rather than primitive types. Automatic conversion to the resulting wrapper types also reduces clutter in code. |
Noncompliant Code Example
Wiki Markup |
---|
This noncompliant code example prints {{100}} as the size of the {{HashSet}} rather than the expected result ({{1}}). The combination of values of types {{short}} and {{int}} in the operation {{i-1}} causes the result to be autoboxed into an object of type {{Integer}}, rather than one of type {{Short}}. See rule "[NUM18-J. Be aware of numeric promotion behavior]" for additional explanation of the details of the promotion rules. The {{HashSet}} contains only values of type {{Short}}; the code attempts to remove objects of type {{Integer}}. Consequently, the {{remove()}} operation accomplishes nothing. The language's type checking guarantees that only values of type {{Short}} can be inserted into the {{HashSet}}. Nevertheless, programmers are free to attempt to remove an object of _any_ type because {{Collections<E>.remove()}} accepts an argument of type {{Object}} rather than of type {{E}}. Such behavior can result in unintended object retention or memory leaks \[[Techtalk 2007|AA. Bibliography#Techtalk 07]\]. |
Code Block | ||
---|---|---|
| ||
public class ShortSet { public static void main(String[] args) { HashSet<Short> s = new HashSet<Short>(); for (shortint i = 0; i < 10010; i++) { s.add((short)i); // Cast required so that the code compiles s.remove(i - 1); // Tries to remove an Integer } System.out.println(s.size()); } } |
This noncompliant code example also violates EXP00-J. Do not ignore values returned by methods because the remove()
method returns a Boolean value indicating its success.
Compliant Solution
Objects removed from a collection must share the type of the collection elements of the collection. Numeric promotion and autoboxing can produce unexpected object types. This compliant solution uses an explicit cast to short
that parallels matches the intended boxed type.
Code Block | ||
---|---|---|
| ||
import java.util.HashSet; public class ShortSet { public static void main(String[] args) { HashSet<Short> s = new HashSet<Short>(); for (shortint i = 0; i < 10010; i++) { s.add((short)i); // Remove a Short if (s.remove((short)(i) -== 1)false); //{ cast to short } System.err.println("Error removing " + i); } } System.out.println(s.size()); } } |
Exceptions
Risk Assessment
EXP04-J-EX1: The collections framework equals()
method also takes an argument of type Object
, but it is acceptable to pass an object of a different type from that of the underlying collection/map to the equals()
method. Doing so cannot cause any confusion because the contract of the equals()
method stipulates that objects of different classes will never be equivalent (see MET08-J. Preserve the equality contract when overriding the equals() method for more information).
EXP04-J-EX2: Some Java programs, particularly legacy programs, may iterate through a collection of variously typed objects with the expectation that only those objects with the same type as the collection parameter will be operated on. An exception is allowed when there is no expectation that the operation is not a no-op.
Risk Assessment
Passing arguments to certain Java Collection Framework methods that are of a different type from that of the class instance can cause silent failures, resulting Allowing autoboxing to produce objects of an unintended type can cause silent failures with some APIs, such as the Collections
library. These failures can result in unintended object retention, memory leaks, or incorrect program operationoperation [Techtalk 2007].
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|
EXP04-J |
Low |
Probable |
Low | P6 | L2 |
Automated Detection
Detection of invocations of Collection.remove()
whose operand fails to match the type of the elements of the underlying collection is straightforward. It is possible, albeit although unlikely, that some of these invocations could be intended. The remainder are heuristically likely to be in error. Automated detection for other APIs could be possible.
Related Guidelines
Bibliography
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
PVS-Studio |
| V6066 | |||||||
SonarQube |
| S2175 | Inappropriate "Collection" calls should not be made |
Bibliography
Chapter 5, "Inheritance" | |
[JCF 2014] | The Java Collections Framework |
[JLS 2015] |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="ccf79a7b-9358-4029-8a7f-fbc62a2debc6"><ac:plain-text-body><![CDATA[
[[Core Java 2004
AA. Bibliography#Core Java 04]]
Chapter 5
]]></ac:plain-text-body></ac:structured-macro>
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="6ae7936b-3e7c-4767-b7bb-fb388021c2b6"><ac:plain-text-body><![CDATA[
[[JLS 2005
AA. Bibliography#JLS 05]]
http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.7]
]]></ac:plain-text-body></ac:structured-macro>
[Seacord 2015] | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="c0873bd1-16cb-4997-9d6f-77bb60ac0ea9"><ac:plain-text-body><![CDATA[
[[Techtalk 2007
] | "The Joy of Sets" |
]]></ac:plain-text-body></ac:structured-macro>
...
EXP06-J. Do not use side-effecting expressions in assertions 02. Expressions (EXP) EXP11-J. Never dereference null pointers