2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
When ``++List.remove()++`` is called it will shrink the list. If this is done inside the ascending loop iterating through all elements it will skip the element after the removed index.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
void removeFrom(List<String> list) {
// expected: iterate over all the elements of the list
for (int i = 0; i < list.size(); i++) {
if (list.get(i).isEmpty()) {
// actual: remaining elements are shifted, so the one immediately following will be skipped
list.remove(i); // Noncompliant
}
}
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
You can either adjust the loop index to account for the change in the size of the list
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
static void removeFrom(List<String> list) {
// expected: iterate over all the elements of the list
for (int i = 0; i < list.size(); i++) {
if (list.get(i).isEmpty()) {
// actual: remaining elements are shifted, so the one immediately following will be skipped
list.remove(i);
i--;
}
}
}
----
Or preferably it's probably better to rely on Java 8's ``++removeIf++`` method
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
static void removeFrom(List<String> list) {
list.removeIf(String::isEmpty);
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Exceptions
2021-04-28 16:49:39 +02:00
The descending loop doesn't have this issue, because the index will be correct when we loop in descending order
----
void removeFrom(List<String> list) {
for (int i = list.size() - 1; i >= 0; i--) {
if (list.get(i).isEmpty()) {
list.remove(i);
}
}
}
----
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
endif::env-github,rspecator-view[]