rspec/rules/S6877/java/rule.adoc

76 lines
2.3 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.
One of the features of the new Sequenced Collections API is `SequencedCollection.reversed()` which returns a lightweight view of the original collection, in the reverse order.
This rule reports when reverse view would have been sufficient instead of a reverse copy of a sequenced collection created using a list constructor plus a `Collections.reverse(collection);` call.
If feasible, a view should be preferred over a copy because a view is a lightweight iterator without modification of the list itself.
== How to fix it
Remove `Collections.reverse(list);` and replace `list` with `list.reversed()` after.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
void foo() {
var list = new ArrayList<String>();
list.add("A");
list.add("B");
Collections.reverse(list); // Noncompliant
for (var e : list) {
// ...
}
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
void foo() {
var list = new ArrayList<String>();
list.add("A");
list.add("B");
for (var e : list.reversed()) { // Compliant
// ...
}
}
----
==== Noncompliant code example
[source,java,diff-id=2,diff-type=noncompliant]
----
void foo(List<String> list) {
var copy = new ArrayList<String>(list);
Collections.reverse(copy); // Noncompliant
for (var e : copy) {
// ...
}
}
----
==== Compliant solution
[source,java,diff-id=2,diff-type=compliant]
----
void foo(List<String> list) {
for (var e : list.reversed()) { // Compliant
// ...
}
}
----
== 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]