Stack 클래스 Stack<E> stack = new Stack<E>();
특징
후입선출(LIFO: Last In First Out) 구조
응용 예: JVM 스택 메모리
주요 메소드
리턴 타입 |
메소드 |
설명 |
E |
push(E item) |
주어진 객체를 스택에 넣는다. |
E |
peek() |
스택의 맨 위에 객체를 가져온다. 객체를 스택에서 제거하지는 않는다. |
E |
pop() |
스택의 맨 위 객체를 가져온다. 객체를 스택에서 제거한다. |
Queue 인터페이스 Queue queue = new LinkedList();
특징
선입선출(FIFO: First In First Out)
응용 예 : 작업큐, 메세지큐, ...
구현 클래스: LinkedList
주요 메소드
리턴 타입 |
메소드 |
설명 |
boolean |
offer(E e) |
주어진 객체를 넣는다. |
E |
peek() |
객체 하나를 가져온다. 객체를 큐에서 제거하지 않는다. |
E |
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을 보냅니다. 박효신님에게 카카오톡을 보냅니다.
'JAVA > JAVA' 카테고리의 다른 글
# 1주차 과제: JVM은 무엇이며 자바 코드는 어떻게 실행하는 것인가 (0) | 2020.12.04 |
---|---|
자바 컬렉션) 동기화된(synchronized) 컬렉션 (0) | 2018.06.16 |
자바 컬렉션) 검색 기능을 강화시킨 컬렉션 (0) | 2018.06.15 |
자바 컬렉션) Map 컬렉션 (0) | 2018.06.14 |
자바 컬렉션) Set 컬렉션 (0) | 2018.06.14 |