import java.util.*;
public class Main {
public static void main(String[] args){
int index = 0;
String structure;
String input;
Scanner sc = new Scanner(System.in);
structure = sc.nextLine();
switch(structure){
case "Set":
Set<String> StrSet = new LinkedHashSet<String>();
while(true){
input = sc.nextLine();
if(input.equals("끝"))
break;
StrSet.add(input);
}
for(String s : StrSet){
if(index==0){
System.out.println("[ "+structure+"으로 저장된 "+s+" ]");
}
else{
System.out.println(index+". "+s);
}
index++;
}
break;
case "Queue":
Queue<String> StrQueue = new LinkedList<>();
while(true){
input = sc.nextLine();
if(input.equals("끝")){
break;
}
else{
StrQueue.add(input);
}
}
while(!StrQueue.isEmpty()){
if(index==0){
System.out.println("[ "+structure+"으로 저장된 "+StrQueue.poll()+" ]");
}
else{
System.out.println(index+". "+StrQueue.poll());
}
index++;
}
break;
case "Map":
Map<Integer, String> StrMap = new HashMap<>();
while(true){
input = sc.nextLine();
if(input.equals("끝")){
break;
}
else{
StrMap.put(index++,input);
}
}
for(Integer key : StrMap.keySet()){
if(key==0){
System.out.println("[ "+structure+"으로 저장된 "+StrMap.get(key)+" ]");
}
else{
System.out.println(key+". "+StrMap.get(key));
}
}
break;
case "List":
ArrayList<String> StrList = new ArrayList<>();
while(true){
input = sc.nextLine();
if(input.equals("끝")){
break;
}
else{
StrList.add(input);
}
}
for(String s : StrList){
if(index==0){
System.out.println("[ "+structure+"으로 저장된 "+s+" ]");
}
else{
System.out.println(index+". "+s);
}
index++;
}
}
}
}
이 숙제를 하면서 Set에 저장된 데이터를 어떻게 순차적으로 출력해야 할 지를 고민했다. Set은 순서가 보장되지 않는 자료형이라 그런지 다른 자료구조와 비슷한 방식으로 출력하려 하니까 순서대로 나오지 않고 랜덤으로 나왔다.
하지만 순서를 기억하는 LinkedHashSet가 있다는 것을 알아냈고 그것을 사용하여 풀었다.
'(2주차) JAVA 문법 종합반 > 2주차' 카테고리의 다른 글
16. 컬렉션 Stack, Queue, Set, Map (0) | 2024.08.05 |
---|---|
15. 컬렉션 List (0) | 2024.08.03 |
14. 컬렉션 소개 (0) | 2024.08.01 |
13. 다차원 배열 및 배열 실습 (0) | 2024.07.31 |
12. 얕은 복사, 깊은 복사, string 배열 (0) | 2024.07.31 |