rspec/rules/S6902/java/rule.adoc
github-actions[bot] 99b1bf6896
Create rule S6902: SequencedCollection methods should be used to get the first or last element (#3596)
* Create rule S6902: SequencedCollection methods should be preferred to get the first or last element

* fix from review

---------

Co-authored-by: alban-auzeill <alban-auzeill@users.noreply.github.com>
Co-authored-by: Alban Auzeill <alban.auzeill@sonarsource.com>
2024-02-05 15:27:23 +01:00

63 lines
2.0 KiB
Plaintext

== Why is this an issue?
Java 21 introduces a new SequencedCollection interface that provides a uniform API for accessing its first and last elements.
The new `getFirst()` and `getLast()` methods offer a consistent way to access elements across `SortedSet`, `NavigableSet`, `LinkedHashSet`, `List` and `Deque` collections.
Because those methods are more concise and readable, they should be used instead of more complex workarounds that recreate the same behavior.
For example, `list.get(list.size() - 1)` can be replaced by `list.getLast()`.
This rule identifies code that can be simplified by using the new `getFirst()` and `getLast()` methods.
== How to fix it
Replace the highlighted code with the corresponding `getFirst()` or `getLast()` methods.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
public String concatenateFirstAndLast(List<String> list) {
return list.get(0) + // Noncompliant
list.get(list.size() - 1); // Noncompliant
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
public String concatenateFirstAndLast(List<String> list) {
return list.getFirst() + // Compliant
list.getLast(); // Compliant
}
----
==== Noncompliant code example
[source,java,diff-id=2,diff-type=noncompliant]
----
public String concatenateFirstAndLast(LinkedHashSet<String> linkedHashSet) {
return linkedHashSet.iterator().next() + // Noncompliant
new ArrayList(linkedHashSet).get(linkedHashSet.size() - 1); // Noncompliant
}
----
==== Compliant solution
[source,java,diff-id=2,diff-type=compliant]
----
public String concatenateFirstAndLast(LinkedHashSet<String> linkedHashSet) {
return linkedHashSet.getFirst() + // Compliant
linkedHashSet.getLast(); // Compliant
}
----
== Resources
=== Documentation
* https://openjdk.org/jeps/431[JEP 431: Sequenced Collections]
* https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/SequencedCollection.html[Java SE 21 API documentation - SequencedCollection]