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