Inspectopedia Help

Suspicious 'List.remove()' in loop

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:

public static void main(String[] args) { process(new ArrayList<>( Arrays.asList("1", "2", "|", "3", "4"))); } static void process(List<String> list) { for (int i = 0; i < list.size(); i++) { if (list.get(i).equals("|")) { list.remove(i); continue; } System.out.println(list.get(i)); } }

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

Locating this inspection

By ID

Can be used to locate inspection in e.g. Qodana configuration files, where you can quickly enable or disable it, or adjust its settings.

SuspiciousListRemoveInLoop
Via Settings dialog

Path to the inspection settings via IntelliJ Platform IDE Settings dialog, when you need to adjust inspection settings directly from your IDE.

Settings or Preferences | Editor | Inspections | Java | Probable bugs

New in 2018.2

Availability

By default bundled with

IntelliJ IDEA 2024.1, Qodana for JVM 2024.1,

Can be installed with plugin

Java, 241.18072

Last modified: 18 June 2024