[Java] Unlikely argument type for Collection methods using Object

java

(Werner Thumann) #1

Description
Some Collection methods like List#remove or Map#get have type Object as arguments. Calling these methods with types unrelated to the type T of e.g. List< T > or Map< T , ? > is most likely unintended and a bug. This is very similar to “Silly equality checks should not be made” (squid:S2159).

Type
Bug

Snippet

public class UnlikelyArgumentTypeForCollectionMethodsUsingObject {

	public static void main(String[] args) {
		Map<Integer,Object> map = new HashMap<>();
		map.remove("a string"); // Noncompliant
		map.remove(8); // Compliant
	}
	
}

Note
Also covered by Eclipse JDT.


(Alexandre Gigleux) #3

Hello Werner,

This one is partially covered by https://rules.sonarsource.com/java/RSPEC-2175.
Today RSPEC-2175 is covering only Collection.remove(Object o) and Collection.contains(Object o).

I updated the specification and created SONARJAVA-2968 to cover Map.
Be aware also that we have https://jira.sonarsource.com/browse/SONARJAVA-2952 to cover the case of custom collections extending standard collections.

Regards