Stack 클래스       Stack<E> stack = new Stack<E>();

특징

후입선출(LIFO:    Last In First Out) 구조

응용 예:     JVM 스택 메모리



주요 메소드

리턴 타입 

메소드 

설명 

 push(E item) 

주어진 객체를 스택에 넣는다. 

 peek() 

스택의 맨 위에 객체를 가져온다. 객체를 스택에서 제거하지는 않는다. 

 pop() 

스택의 맨 위 객체를 가져온다. 객체를 스택에서 제거한다. 




Queue 인터페이스         Queue queue = new LinkedList();

특징

선입선출(FIFO:    First In First Out)

응용 예 :     작업큐,    메세지큐, ...

구현 클래스:    LinkedList

주요 메소드

리턴 타입 

메소드 

설명 

boolean 

offer(E e) 

주어진 객체를 넣는다. 

peek() 

객체 하나를 가져온다. 객체를 큐에서 제거하지 않는다. 

pool() 

개체 하나를 가져온다. 객체를 큐에서 제거한다. 


Exam stack  LIFO

public class Coin {
private int value;

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

public int getValue() {
return value;
}
}
public class StackExample {
public static void main(String[] args) {
Stack<Coin> coinBox = new Stack<>();

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());
}
}
} 꺼내온 동전 = 10 꺼내온 동전 = 500 꺼내온 동전 = 50 꺼내온 동전 = 100

Exam2   Queue FIFO

public class Message {
public String command;
public String to;

public Message(String command, String to) {
this.command = command;
this.to = to;
}
}
import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
public static void main(String[] args) {

Queue<Message> messageQueue = new LinkedList<>();

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;
}
}
}
} 김나박님에게 메일을 보냅니다. 나얼님에게 SMS을 보냅니다. 박효신님에게 카카오톡을 보냅니다.


+ Recent posts