- LIFO(Last In First Out)
: 나중에 넣은 객체가 먼저 빠져나가는 구조
- FIFO(First In First Out)
: 먼저 넣은 객체가 먼저 빠져나가는 자료구조
→ 컬렉션 프레임워크에는
LIFO(리포) 자료구조를 제공하는 Stack 클래스와
FIFO(피포) 자료구조를 제공하는 Queue 인터페이스를
제공하고 있음
: Stack 클래스는 LIFO 자료구조를 구현한 클래스
: Stack 객체를 생성하려면
저장할 객체 타입을 E 타입 파라미터 자리에 표기하고
기본 생성자를 호출하면 됨
ex) String을 저장하는 Stack
Stack<E> stack = new Stack<E>();
Stack<E> stack = new Stack<>();
import java.util.*;
/*
* 동전 케이스는 위에만 열려 있는 스택 구조를 가짐
* 먼저 넣은 동전은 제일 밑에 깔리고
* 나중에 넣은 동전이 위에 쌓이기 때문에
* Stack에서 동전을 빼면 마지막에 넣은 동전이
* 먼저 나오게 됨
*/
// 동전 클래스
class Coin {
private int value;
public Coin(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
// 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() + "원");
}
}
}
💻 결과
꺼내온 동전: 10원
꺼내온 동전: 500원
꺼내온 동전: 50원
꺼내온 동전: 100원
: Queue 인터페이스는 FIFO 자료구조에서 사용되는 메소드를 정의하고 있음
: Queue 인터페이스를 구현한
대표적인 클래스는 LinkedList임
LInkedList는 List 인터페이스를 구현했기 때문에
List 컬렉션이기도 함
- LinkedList 객체를 Queue 인터페이스 타입으로 변환한 것
Queue<E> queue = new LinkedList<E>();
Queue<E> queue = new LinkedList<>();
import java.util.*;
/*
* 먼저 넣은 메시지가
* 반대쪽으로 먼저 나오기 떄문에
* 넣은 순서대로 메시지가 처리됨
*/
// Message 클래스
class Message {
public String command;
public String to;
public Message(String command, String to) {
this.command = command;
this.to = to;
}
}
// Queue를 이용한 메시지 큐
public class QueueExample {
public static void main(String[] args) {
Queue<Message> messageQueue = new LinkedList<Message>();
messageQueue.offer(new Message("sendMail", "홍길동1"));
messageQueue.offer(new Message("sendMail", "홍길동2"));
messageQueue.offer(new Message("sendMail", "홍길동3"));
while(!messageQueue.isEmpty()) {
// 메시지 큐에서 1개의 메시지 꺼냄
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;
}
}
}
}
💻 결과
홍길동1님에게 메일을 보냅니다.
홍길동2님에게 메일을 보냅니다.
홍길동3님에게 메일을 보냅니다.