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)
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' } } }