62 lines
2.0 KiB
Plaintext
62 lines
2.0 KiB
Plaintext
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
|
|
|
|
[source,java]
|
|
----
|
|
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
|
|
|
|
* https://wiki.sei.cmu.edu/confluence/x/uDdGBQ[CERT, EXP04-J.] - Do not pass arguments to certain Java Collections Framework methods that are a different type than the collection parameter type
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|