개발자 도전기
[JAVA] Stack, Queue 본문
LIFO와 FIFO 컬렉션
후입선출(LIFO)은 나중에 넣은 객체가 먼저 빠져나가고, 선입선출(FIFO)은 먼저 넣은 객체가 먼저 빠져나가는 구조를 말한다. 컬렉션 프레임워크는 LIFO 자료구조를 제공하는 스택(Stack) 클래스와 FIFO 자료구조를 제공하는 큐(Queue) 인터페이스를 제공하고 있다.
Stack
Stack 클래스는 LIFO 자료구조를 구현한 클래스이다. 다음은 Stack 객체를 생성하는 방법이다
Stack<E> stack = new Stack<>();
Stack 클래스의 주요 메소드이다
리턴 타입 | 메소드 | 설명 |
E | push(E item) | 주어진 객체를 스택에 넣는다 |
E | pop() | 스택의 맨 위 객체를 빼낸다 |
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> stack = new Stack<>();
stack.push(new Coin(100));
stack.push(new Coin(50));
stack.push(new Coin(500));
stack.push(new Coin(10));
while (!stack.isEmpty()) {
Coin coin = stack.pop();
System.out.println("꺼내온 동전:" + coin.getValue() + "원");
}
}
}
Queue
Queue 인터페이스는 FIFO 자료구조에서 사용되는 메소드를 정의하고 있다.
다음은 Queue 인터페이스에 정의되어 있는 메소드이다
리턴 타입 | 메소드 | 설명 |
boolean | offer(E e) | 주어진 객체를 큐에 넣는다 |
E | poll() | 큐에서 객체를 빼낸다 |
Queue는 인터페이스이기 때문에 직접 객체를 생성할 수는 없고 대신 Queue 인터페이스를 구현한 LinkedList 클래스의 객체를 대입할 수 있다.
Queue<E> queue = new LinkedList<>();
다음은 Queue를 이용해서 간단한 메세지 큐를 구현한 예제이다
public class Message {
public String command;
public String to;
public Message(String command, String to) {
this.command = command;
this.to = to;
}
}
public class QueueExample {
public static void main(String[] args) {
Queue<Message> queue = new LinkedList<>();
queue.offer(new Message("sendMail", "홍길동"));
queue.offer(new Message("sendSMS", "신용권"));
queue.offer(new Message("sendKakaotalk", "김자바"));
while (!queue.isEmpty()) {
Message message = queue.poll();
switch (message.command) {
case "sendMail" -> System.out.println(message.to + "님에게 메일을 보냅니다");
case "sendSMS" -> System.out.println(message.to + "님에게 SMS를 보냅니다");
case "sendKakaotalk" -> System.out.println(message.to + "님에게 카카오톡을 보냅니다");
}
}
}
}
'개발공부 > JAVA' 카테고리의 다른 글
[JAVA] 수정할 수 없는 컬렉션 (0) | 2024.03.21 |
---|---|
[JAVA] Stream API (0) | 2024.03.21 |
[JAVA] Map 컬렉션 (0) | 2024.03.20 |
[JAVA] 제네릭(Generic) (0) | 2024.03.19 |
[JAVA] 포장 클래스 (0) | 2024.03.19 |