--- id: java-iterator title: "Java Iterator" category: "Programming_Language" status: "draft" verification_status: "conceptual" canonical_id: "" aliases: ["자바 이터레이터"] duplicate_of: "" source_trust_level: "B" confidence_score: 0.9 created_at: 2026-07-04 updated_at: 2026-07-04 review_reason: "" merge_history: [] tags: ["java", "programming", "w3schools", "collections-framework", "iterator"] raw_sources: ["https://www.w3schools.com/java/java_iterator.asp"] applied_in: [] github_commit: "" --- # [[Java Iterator]] ## 🎯 한 줄 통찰 (One-line insight) Removing elements while looping REQUIRES an Iterator's own `remove()` method — the source explicitly warns that a for loop or for-each loop would NOT work correctly for conditional removal, since the collection changes size mid-loop; only `Iterator.remove()` is designed to safely mutate the collection during iteration. [S1] ## 🧠 핵심 개념 (Core concepts) - **`Iterator`** — an object for looping through collections (ArrayList, HashSet, etc.); "iterating" = the technical term for looping. [S1] - **`.iterator()`** — obtains an Iterator from any collection. [S1] - **`hasNext()` / `next()`** — standard loop pattern: check then advance. [S1] - **`remove()`** — Iterator-specific method that safely removes the current element DURING iteration. [S1] - **Unsafe alternative** — for/for-each loops break when the collection's size changes mid-loop; only Iterator.remove() handles this correctly. [S1] ## 📖 세부 내용 (Details) - Get iterator and print first: `Iterator it = cars.iterator(); System.out.println(it.next());`. [S1] - Full loop: `while(it.hasNext()) { System.out.println(it.next()); }`. [S1] - Safe conditional removal: `ArrayList numbers = ...; Iterator it = numbers.iterator(); while(it.hasNext()) { Integer i = it.next(); if(i < 10) { it.remove(); } }`. [S1] ## ⚖️ 모순 및 업데이트 (Contradictions & updates) - **for/for-each 루프의 위험성**: 컬렉션 순회 중 요소를 제거하려면 for 루프나 for-each 루프는 올바르게 동작하지 않는다는 점이 명시적으로 경고됨 — 반드시 Iterator.remove() 사용. [S1] ## 🛠️ 적용 사례 (Applied in summary) 현재 발견된 실제 적용 사례가 없습니다 — 10 미만의 숫자를 컬렉션에서 제거하는 예제가 순회 중 안전한 삭제의 표준 패턴이다. [S1] ## 💻 코드 패턴 (Code patterns) Safely removing elements during iteration (Java): ```java ArrayList numbers = new ArrayList(); numbers.add(12); numbers.add(8); numbers.add(2); numbers.add(23); Iterator it = numbers.iterator(); while (it.hasNext()) { Integer i = it.next(); if (i < 10) { it.remove(); // safe removal during iteration } } ``` ## ✅ 검증 상태 및 신뢰도 - **상태:** draft - **검증 단계:** conceptual - **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body) - **신뢰 점수:** 0.90 - **중복 검사 결과:** 신규 생성 (New discovery) ## 🔗 지식 그래프 (Knowledge Graph) - **상위/루트:** [[Java Tutorial]] - **관련 개념:** [[Java ArrayList]], [[Java HashSet]], [[Java For Each Loop]], [[Java Algorithms]] - **참조 맥락:** 자료구조 공통 순회 도구 — Data Structures & Collections 섹션의 마지막, Advanced(알고리즘) 섹션으로 이어짐. ## 📚 출처 (Sources) - [S1] W3Schools — Java Iterator — https://www.w3schools.com/java/java_iterator.asp ## 📝 변경 이력 (Change history) - 2026-07-04: Initial draft synthesized from the W3Schools "Java Iterator" page (Astra wiki-curation, P-Reinforce v3.1 format).