rspec/rules/S6877/java/rule.adoc

47 lines
2.1 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
Java 21 introduces the new Sequenced Collections API, which applies to all collections with a defined sequence on their elements, such as `LinkedList`, `TreeSet`, and others (see https://openjdk.org/jeps/431[JEP 431]).
For projects using Java 21 and onwards, use this API instead of workaround implementations that were necessary before Java 21.
This rule reports when a reverse copy of a list is created, but a reverse view would have been sufficient because the resulting list - as well as the original list in the scope of the resulting list - is not modified (`add`, `remove`).
`SequencedCollection.reversed()` returns a view of the original list that reflects changes in the original list, while `Collection.reverse(List)` creates a new list that is not connected with the original list.
If feasible, a view should be preferred over a copy because:
1. It is a lightweight collection that only functions as a view and it does not allocate memory for the data contained in the underlying collection.
2. It abstracts from the fact that the collection instance is a list. This results in more generic code that is easier to port, for instance, when you want to use another collection data structure.
== How to fix it
Replace `Collection.reverse(list)` with `list.reversed()`.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
void foo(List<String> list) {
var reverseList = Collections.reverse(list); // Noncompliant
// ... (read-only operations)
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
void foo(List<String> list) {
var reverseList = list.reversed(); // Compliant
// do something
// ...
}
----
== Resources
=== Documentation
* Java Documentation - https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/SequencedCollection.html[Interface SequencedCollection]
* OpenJDK - https://openjdk.org/jeps/431[JEP 431: Sequenced Collections]
* Java Documentation - https://docs.oracle.com/en/java/javase/21/core/creating-sequenced-collections-sets-and-maps.html#GUID-DCFE1D88-A0F5-47DE-A816-AEDA50B97523[Creating Sequenced Collections, Sets, and Maps]