{"record":{"id":"dc212cb03c2f42b1","repo":"TheAlgorithms/Java","slug":"cannot-remove-element-before-calling-next","errorCode":null,"errorMessage":"Cannot remove element before calling next()","messagePattern":"Cannot remove element before calling next\\(\\)","errorType":"exception","errorClass":"IllegalStateException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java","lineNumber":258,"sourceCode":"        public E next() {\n            checkForComodification();\n            if (cursor >= size) {\n                throw new NoSuchElementException();\n            }\n            return (E) elements[cursor++];\n        }\n\n        /**\n         * Removes the last element returned by this iterator.\n         *\n         * @throws IllegalStateException if the next method has not yet been called, or\n         *                               the remove method has already been called after\n         *                               the last call to the next method\n         */\n        @Override\n        public void remove() {\n            if (cursor <= 0) {\n                throw new IllegalStateException(\"Cannot remove element before calling next()\");\n            }\n            checkForComodification();\n            DynamicArray.this.remove(--cursor);\n            expectedModCount = modCount;\n        }\n\n        /**\n         * Checks for concurrent modifications to the array during iteration.\n         *\n         * @throws ConcurrentModificationException if the array has been modified\n         *                                         structurally\n         */\n        private void checkForComodification() {\n            if (modCount != expectedModCount) {\n                throw new ConcurrentModificationException();\n            }\n        }\n","sourceCodeStart":240,"sourceCodeEnd":276,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java#L240-L276","documentation":"The DynamicArray iterator's remove() follows the standard Java Iterator contract: it can only be called once per next() call. The cursor starts at 0; calling remove() before any next() (cursor <= 0) or calling it twice after a single next() (cursor was decremented back to 0) throws IllegalStateException.","triggerScenarios":"Calling iterator.remove() before any iterator.next(). Calling remove() twice without an intervening next(). Calling remove() on a fresh iterator without advancing.","commonSituations":"Forgetting to call next() inside a while(hasNext()) loop before remove(). Calling remove() in a filter predicate without advancing the iterator. Copy-paste of a removal pattern that omits the next() call.","solutions":["Always call next() immediately before remove() in the loop body","Use the stream API or a collection removeIf pattern instead of manual iterator removal","Track whether next() was called with a boolean flag if the removal is conditional"],"exampleFix":"// before — remove() called before next()\nIterator<String> it = arr.iterator();\nwhile (it.hasNext()) {\n    it.remove(); // throws IllegalStateException\n    it.next();\n}\n\n// after — next() before remove()\nIterator<String> it = arr.iterator();\nwhile (it.hasNext()) {\n    String e = it.next();\n    if (shouldRemove(e)) it.remove();\n}","handlingStrategy":"validation","validationCode":"// Ensure next() is called before remove().\nIterator<String> it = arr.iterator();\nboolean canRemove = false;\nwhile (it.hasNext()) {\n    String e = it.next();\n    canRemove = true;\n    if (shouldRemove(e)) {\n        it.remove();\n        canRemove = false; // must call next() again before next remove()\n    }\n}","typeGuard":null,"tryCatchPattern":"try {\n    it.remove();\n} catch (IllegalStateException e) {\n    // next() was not called or remove() was called twice — skip\n    logger.debug(\"Iterator.remove() called in illegal state\");\n}","preventionTips":["Always call next() before remove() in the loop body","For filtering, prefer stream().filter() or removeIf() over manual iterator removal","After calling remove(), do not call it again until after the next next()"],"tags":["dynamic-array","iterator","illegal-state"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}