java:S6204 should not raise an issue when addFirst/-Last, removeFirst/-Last is called on the list

Rule S6204 intent is to use unmutable lists instead of mutable lists whenever possible. Specifically, the rule correctly suggests replacing stream.collect(Collectors.toList()); with stream.toList(); when there is no modification detected on the returned list, and thus, it is incorrect to define it as a mutable list.

To this end the rule recognizes several methods on List that constitute a modification and allows like e.g. add, set and others

Beginning with Java 21 List implements SequencedCollection and 4 additional methods modify the list and the rule must not suggest the use of Stream::toList().

i.e. List::addFirst, List::addLast, List::removeFirst, List::removeLast

Suggested implementation, see PR:

___________________

Discussion:

This is similar to the already solved case for removeIf:

Several other open issues discuss this rule java:S6204 but not specifically the use of these methods:

Hi,

Can you give your context for this false-negative? I.e. are you on SonarQube Cloud? SonarQube for IDE (flavor and version)? SonarQube self-managed (flavor and version)?

 
Thx,
Ann

Hi,

I have seen it on our clients self hosted SonarQube Server, Community Build v25.12.0.11709.
Is that information useful?

As you might have noticed, I have already sent a PR including tests for this (SONARJAVA java:S6204 should not raise an issue when addFirst/addLast/removeFirst/removeLast is called on the list by Jmanom · Pull Request #5382 · SonarSource/sonar-java · GitHub).
Maybe that clarifies more than my overly wordy description.

1 Like

Hi,

Thanks for the context. Yes, it’s very helpful!

I’ll flag this for the language experts.

 
Ann