Possible false postive for java:S2175 while using generic wrapping class

Problem description

Rule “java:S2175 Inappropriate “Collection” calls should not be made” triggers if a list is used within a class that itself uses a generic that is also used by the list. If the class provides a method that takes an object of the given type the rules does not recognise that it is the same type that is used in the list.

The same applys for remove.

Expected behaviour

The rule should recognise if a passed generic type is of the same type as the one used in the list and should not trigger.

Used Versions

  • SonarQube Server: Community EditionVersion 8.9.1 (build 44547)
  • SonarLint (IJ): 5.0.1.33703
import java.util.ArrayList;
import java.util.List;

public class Foo<T extends Bar> {
	
	private final List<T> list;
	
	public Foo() {
		this.list = new ArrayList<>();
	}
	
	public void add(final T object) {
		if (!list.contains(object)) {
			list.add(object);
		}
	}
}
public interface Bar {
} 

A few words

I talk about this with some collegues and none could explain why this happens. The examples in the rule make sense but are not wrapped in another generic class and it seem the T in the method is not recognised as the same in List or the class.

For simplification the example was created. Our IRL use case is a class that holds multiple lists of some type.

Maybe i am wrong / missing something but to me it seems like Sonar should be aware of the bounds and not complain about it.

Greetings

PS: I searched and found nothing that states this problem

Hello @rzillmann
and thanks for joining the SonarSource community, and for assembling these details and an example!

An example that I have analyzed on SQ 8.9.1 as well and does not reproduce the false positive. Was it intended to reproduce it? Did it work (i.e. not work :slight_smile: ) on your end?

Best regards
Sylvain

I was hoping that this would not happen…

For clarification. Without doing anything first the IRL code “fixed” itself and today morning the example did not have the message anymore either. The moment the code was clean yesterday i checked the example and was relieved to see, that the message was still there.

I can’t tell you what has happend as nothing “obvious” has changed but we too had some people for which the error was not shown.

So maybe let some other people try it too?

But as the situation is documented here and the problem “vanished” i would be ok with closing the issue too, if you want :slight_smile:

Best regards
Robert

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.