java:S3740: False positive when used with instanceof

Platform: SonarCloud
Language: Java 19
Rule: S3740

False positive is reported for code similar to this:

1 |   Object strings = List.of("A", "B");
2 |   boolean expression = strings instanceof List stringList && stringList.size() > 1;

Problem reported on line 2 seems to be a false positive, as it’s not possible to specify e.g. strings instanceof List<String> stringList.

1 Like

Hello @grimsa,

Thank you for sharing your concerns about rule S3740, and, indeed, there are ambiguous cases to handle properly.

In your specific case, though, the code can be made compliant using an unbound wildcard:

Object strings = List.of("A", "B");
boolean expression = strings instanceof List<?> stringList && stringList.size() > 1;

I created [SONARJAVA-4529] - Jira to discuss and tackle the possible corner cases of rule S3740, feel free to check its progress status.


1 Like