Files
openide/java/java-impl/resources/inspectionDescriptions/SuspiciousListRemoveInLoop.html
Leonid Shalupov 40795fe787 IJI-2422: community/java: move resources under resources root
GitOrigin-RevId: 8b2b63fc6db476ca0c2cfe5cadd84db6c4236d0f
2025-02-05 04:43:28 +00:00

32 lines
1.1 KiB
HTML

<html>
<body>
Reports <code>list.remove(index)</code> calls inside an ascending counted loop.
<p>
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 <code>removeIf()</code> method (Java 8 and later) is a more robust alternative.
If you don't expect that <code>remove()</code> will be called more than once in a loop, consider adding a <code>break</code> after it.
</p>
<p><b>Example:</b></p>
<pre><code> public static void main(String[] args) {
process(new ArrayList&lt;>(
Arrays.asList("1", "2", "|", "3", "4")));
}
static void process(List&lt;String&gt; list) {
for (int i = 0; i &lt; list.size(); i++) {
if (list.get(i).equals("|")) {
list.remove(i);
continue;
}
System.out.println(list.get(i));
}
}
</code></pre>
<p>The code looks like <code>1 2 3 4</code> is going to be printed, but in reality, <code>3</code> will be skipped in the output.</p>
<!-- tooltip end -->
<p><small>New in 2018.2</small></p>
</body>
</html>