Skip to content

Bug: removeOldestItems removes wrong elements (RecentFilesService.java) #202

@Ferki-git-creator

Description

@Ferki-git-creator

There is a logic issue in "RecentFilesService.java", specifically in the method:

private void removeOldestItems(String url)

Problematic code section:

int lastIndex = items.size();
int skip = items.size() - MAX_ELEMENTS_STORED;

for (String item : items) {
counter++;

if (counter != lastIndex && item.equals(url)) {
    continue;
}

if (counter <= skip) {
    continue;
}

newItems.add(item);

}

Issue:
The logic mixes two operations in one pass:

  1. Removing duplicates ("item.equals(url)")
  2. Trimming list to "MAX_ELEMENTS_STORED" using "skip"

Because "skip" is calculated before duplicates are removed, the effective indices shift during iteration. This leads to inconsistent behavior where the wrong elements may be removed, and the list may not correctly preserve the most recent items.

Why this is problematic:

  • "skip = size - MAX_ELEMENTS_STORED" assumes a fixed list size
  • but items are conditionally skipped (duplicates removed) during iteration
  • resulting list does not reliably represent "latest N items"

Expected behavior:

  • Remove all previous occurrences of "url"
  • Add the new "url" as most recent
  • Trim list from the beginning to keep only last "MAX_ELEMENTS_STORED" items

Suggested fix (simpler & deterministic):

items.remove(url);
items.add(url);

while (items.size() > MAX_ELEMENTS_STORED) {
items.remove(0);
}

Notes:
This bug is non-obvious because the logic appears correct at first glance but breaks due to mutation during iteration.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions