Inspectopedia
 
2024.3

Suspicious 'List.remove()' in loop

Warning
New
Last modified: 03 December 2024

Reports list.remove(index) calls inside an ascending counted loop.

This is suspicious as the list becomes shorter after the removal, and the next element gets skipped. A simple fix is to decrease the index variable after the removal, but probably removing via an iterator or using the removeIf() method (Java 8 and later) is a more robust alternative. If you don't expect that remove() will be called more than once in a loop, consider adding a break after it.

Example:

The code looks like 1 2 3 4 is going to be printed, but in reality, 3 will be skipped in the output.

New in 2018.2