JAVA chapter15. 컬렉션 프레임워크


15.6 LIFO와 FIFO 컬렉션


15.6.1 Stack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package sec06.exam01_stack;
 
import java.util.Stack;
 
public class StackExample {
    public static void main(String[] args) {
        Stack<Coin> coinBox = new Stack<Coin>();
        
        coinBox.push(new Coin(100));
        coinBox.push(new Coin(50));
        coinBox.push(new Coin(500));
        coinBox.push(new Coin(10));
        
        while(!coinBox.isEmpty()) {
            Coin coin = coinBox.pop();
            System.out.println("꺼내온 동전 : " + coin.getValue() + "원");
        }
    }
}
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
package sec06.exam01_stack;
 
public class Coin {
    private int value;
    
    public Coin(int value) {
        this.value = value;
    }
    
    public int getValue() {
        return value;
    }
}
cs



15.6.2 Queue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package sec06.exam02_queue;
 
import java.util.LinkedList;
import java.util.Queue;
 
public class QueueExample {
    public static void main(String[] args) {
        Queue<Message> messageQueue = new LinkedList<Message>();
        
        messageQueue.offer(new Message("sendMail""홍길동"));
        messageQueue.offer(new Message("sendSMS""신용권"));
        messageQueue.offer(new Message("sendKakaotalk""홍두께"));
        
        while(!messageQueue.isEmpty()) {
            Message message = messageQueue.poll();
            switch(message.command) {
                case "sendMail":
                    System.out.println(message.to + "님에게 메일을 보냅니다.");
                    break;
                case "sendSMS":
                    System.out.println(message.to + "님에게 SMS를 보냅니다.");
                    break;
                case "sendKakaotalk"
                    System.out.println(message.to + "님에게 카카오톡를 보냅니다.");
                    break;
            }
        }
    }
}
cs

1
2
3
4
5
6
7
8
9
10
11
package sec06.exam02_queue;
 
public class Message {
    public String command;
    public String to;
    
    public Message(String command, String to) {
        this.command = command;
        this.to = to;
    }
}
cs









Posted by 너래쟁이
: