rspec/rules/S6876/java/rule.adoc

44 lines
1.6 KiB
Plaintext

== Why is this an issue?
Java 21 introduces the new Sequenced Collections API, which is applicable 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, this API should be utilized instead of workaround implementations that were necessary before Java 21.
This rule reports when a collection is iterated in reverse through explicit implementation or workarounds, instead of using the reversed view of the collection.
== How to fix it
Replace the reported statement with a forward-iteration over the reversed view of the collection.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
void printLastToFirst(List<String> list) {
for (var it = list.listIterator(list.size()); it.hasPrevious();) {
var element = it.previous();
System.out.println(element);
}
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
void printLastToFirst(List<String> list) {
for (var element: list.reversed()) {
System.out.println(element);
}
}
----
== 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]