내배캠 주요 학습/TIL : Today I Learned
0523_TIL : Iterator 필요성
chaeyoung-
2023. 5. 23. 20:56
# 문제점 : set과 List를 같이 사용할 경우 각자 다른 코드를 입력하여 코드가 좋지 못했다.
switch (dataStructure){
case "Set" :
Set<String> cookRecipeSet = new HashSet<>();
for(int i=0;i<10;i++) {
cookRecipeSet.add(sc.nextLine());
}
System.out.println("\n[ " + dataStructure + " 으로 저장된 " + cookName);
int num=1;
for(String value : cookRecipeSet){
System.out.println(num + ". " + value);
num++;
}
cookRecipeSet.clear();
break;
case "List" :
ArrayList<String> cookRecipeList = new ArrayList<String>();
for(int i=0;i<10;i++) {
cookRecipeList.add(sc.nextLine());
}
System.out.println("\n[ " + dataStructure + " 으로 저장된 " + cookName);
num=1;
for(String value : cookRecipeList){
System.out.println(num + ". " + value);
num++;
}
cookRecipeList.clear();
break;
case "Map" :
Map<Integer, String> cookRecipeMap = new HashMap<>();
for(int i=1;i<11;i++) {
cookRecipeMap.put(i,sc.nextLine());
}
System.out.println("\n[ " + dataStructure + " 으로 저장된 " + cookName);
num = 1;
for(String value : cookRecipeMap.values()){
System.out.println(num + ". " + value);
num++;
}
cookRecipeMap.clear();
break;
default:
System.out.println("잘못된 자료 구조를 입력하셨습니다.");
break;
}
# 해결방법 : 유지보수성을 향상 시키기 위해 Iterator를 사용
- 조언해주신 분 : 상의성 스승님
Set 타입에는 get 메서드가 없어서 Set과 List를 출력할 때 각각 코드를 따로 입력했다.
하지만 아래와 같이 Iterator을 사용하면 한번만 입력해도 출력이 가능하다.
Iterator<String> iterSet = stringSet.iterator();
int cnt = 0;
while(iterSet.hasNext()) {
++cnt;
System.out.println(cnt + ". " + iterSet.next());
}