Quick Answer

Occurs when method is called at illegal/inappropriate time.

Understanding the Issue

This runtime exception indicates a method was called when the object was in an inappropriate state (e.g., using an iterator after collection modification).

The Problem

This code demonstrates the issue:

Java Error
// Problem: Iterator misuse
List<String> list = new ArrayList<>();
Iterator<String> it = list.iterator();
list.add("new item");  // Modifies after iterator creation
it.next();  // Throws IllegalStateException

The Solution

Here's the corrected code:

Java Fixed
// Solution 1: Proper iteration
Iterator<String> it = list.iterator();
while(it.hasNext()) {
    String item = it.next();
    // Safe to call it.remove() here
}

// Solution 2: Concurrent collections
List<String> safeList = new CopyOnWriteArrayList<>();

Key Takeaways

Never modify collections during iteration; use concurrent collections when needed.