Menu

Java Tricky Question: Why Does Removing From an ArrayList Inside a for-each Loop Crash Only Sometimes?
📰

Java Tricky Question: Why Does Removing From an ArrayList Inside a for-each Loop Crash Only Sometimes?

DEV Community: tutorial·Vishnu B·about 18 hours ago
#VeifcLpj
#devtotutorial#devto#dev#iterator#java
Long article (1513 words) — no AI summary yet.
Reading 0:00
15s threshold

Here is a scenario that surprises people in interviews and in real code. Look at this tiny program and predict what it does.

import java . util . ArrayList ; import java . util . List ;

public class CrashDemo { public static void main ( String [ ] args ) { List < String > names = new ArrayList <> ( ) ; names . add ( "ana" ) ; names . add ( "bo" ) ; names . add ( "cy" ) ; names . add ( "dan" ) ;

for ( String name : names ) { System . out . println ( "visiting " + name ) ; if ( name . equals ( "bo" ) ) { names . remove ( name ) ; // remove the element while looping } } System . out .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.