Java 개념

Stack과 Queue

ron_nie 2023. 8. 23. 21:03
728x90

1. Stack

Stack 클래스는 LIFO 자료구조를 구현한 클래스이다

1-1. 생성

Stack<E> stack = new Stack<E>();
Stack<E> stack = new Stack<>();

1-2. 활용 

package trainingStackQueue.stackCoin;

import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {
        // Stack 컬렉션 생성
        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() + "원");
        }
    }
}
package trainingStackQueue.stackCoin;

public class Coin {
    private int value;

    public Coin(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

2. Queue

2-1. 생성

Queue<E> Queue = new LinkedList<E>();
Queue<E> queue = new LinkedList<>();

2-2. 활용 

package trainingStackQueue.stackCoin.QueueMessage;

public class Meassage {
    public String commend;
    public String to;

    public Meassage(String commend, String to) {
        this.commend = commend;
        this.to = to;
    }
}
package trainingStackQueue.stackCoin.QueueMessage;

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
    public static void main(String[] args) {
        // Queue 컬렉션 생성
        Queue<Meassage> messageQueue = new LinkedList<>();

        // 메세지 넣기
        messageQueue.offer(new Meassage("sendMail", "홍길동"));
        messageQueue.offer(new Meassage("sendSMS", "신용권"));
        messageQueue.offer(new Meassage("sendKaKaotalk", "김자바"));

        // 메세지를 하나씩 꺼내어 처리
        while (!messageQueue.isEmpty()){
            Meassage meassage = messageQueue.poll();
            switch (meassage.commend){
                case "sendMail":
                    System.out.println(meassage.to + "님에게 메일을 보냅니다.");
                    break;
                case "sendSMS":
                    System.out.println(meassage.to + "님에게 SMS를 보냅니다.");
                    break;
                case "sendKaKaotalk":
                    System.out.println(meassage.to + "님에게 카카오톡을 보냅니다.");
                    break;
            }
        }
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형