오류, 기능, 문제해결(JAVA)

내배캠 2주차 자바 숙제 풀다가 iterator() 관련 문제

seungmin576 2024. 12. 31. 20:44

 

 

package week2.collection;

import java.util.*;

public class Exercise {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String collection = sc.nextLine();
        String foodName = sc.nextLine();

        System.out.println("[ " + collection + " 으로 저장된 " + foodName + " 만들기 ]");

        switch (collection) {
            case "List" :
                ArrayList<String> list = new ArrayList<>();
                int i = 0;
                while(true) {
                    list.add(sc.nextLine());
                    if(list.get(i).equals("끝"))
                        break;
                    System.out.println(i + 1 + "." + list.get(i));
                    i++;
                }
                break;
            case "Set" :
                i = 0;
                Set<String> list2 = new LinkedHashSet<>();
                while (true) {
                    list2.add(sc.nextLine());
                    if(list2.contains("끝"))
                        break;
                    Iterator<String> iterator = list2.iterator();
                    String str = iterator.next();
                    System.out.println(i + 1 + "." + str);
                    i++;
                }
                break;
        }

    }
}

case : "Set"을 보면 Iterator를 사용하여 출력을 반복하게 했다.

그랬더니 입력받은 첫번째 요소만 출력하여 원하는 결과가 나오지 않는다.

그 이유가 뭔지 궁금하여 찾아봤더니 Iterator는 Set의 요소를 순회하기 위해 사용된다.

그러나 현재 코드에서는 Iterator를 매 반복마다 새로 생성하고, iterator.next()를 호출하여 첫 번째 요소만 가져오고 있다. 이 경우, iterator는 항상 Set의 첫 번째 요소를 가리키게 된다.

영상 강의가 컬렉션에 대해서 깊지 않게 빠르게 훑고 지나가는데 iterator에 대한 내용도 없어서 직접 찾아서 쓰려니 이런 점을 몰랐고 위의 이유 때문에 그랬던 것이다.

 

  • 구조바꾸기
while (true) {
                    list2.add(sc.nextLine());
                    if(list2.contains("끝")) {
                        list2.remove("끝");
                        break;
                    }
                }
                Iterator<String> iterator = list2.iterator();
                while(iterator.hasNext()) {
                    String item = iterator.next();
                    System.out.println(i + 1 + "." + item);
                    i++;
                }
                break;

첫번째 while 문 안에서 iterator 관련 코드를 지우고 만약 "끝"이 포함된다면 "끝"을 삭제하고 반복을 끝내게 한다.

첫번째 while 밖에 iterator를 선언(아깐 반복문 안에서 선언 계속 새로되서 문제였다), 대입 한 뒤 while을 돌려 hasNext()로 요소가 있는 동안 반복 조건을 설정해 주고 item을 새로 선언하여 iterator.next()의 값을 대입한다.

인터넷을 뒤져보니 iterator를 사용하려면 while 문을 이용해 hasNext()를 조건에 걸고 next() 값을 출력하는게 공식인듯하다.

다음부터는 이렇게 해야겠다.

 


Iterator<String> iterator = list2.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next()); // 모든 요소 출력
}

iterator를 사용하여 모든 요소 출력하는 방법.