Queue는 먼저 들어온 데이터가 먼저 나가는(First-In-First-Out) 구조.
주로 작업 예약, 메시지 처리, 버퍼 등 순차적 처리에 많이 사용한다.
자바에서는 java.util.Queue 인터페이스로 제공된다.
자바에서는 Queue 인터페이스를 직접 사용할 수 없고, 다음과 같은 구현체를 사용한다:
| 구현 클래스 | 특징 |
|---|---|
LinkedList | 가장 대표적인 큐 구현체. 일반 큐, 덱(Deque) 모두 가능 |
ArrayDeque | 배열 기반의 덱. 스택/큐 모두로 사용 가능 |
PriorityQueue | 우선순위 큐. 요소가 우선순위에 따라 정렬됨 |
| 메서드 | 설명 |
|---|---|
add(E e) | 큐에 요소 추가. 공간이 없으면 예외 발생 |
offer(E e) | 큐에 요소 추가. 공간 없으면 false 반환 |
remove() | 큐에서 요소 제거 후 반환. 비어있으면 예외 발생 |
poll() | 큐에서 요소 제거 후 반환. 비어있으면 null 반환 |
element() | 큐의 첫 요소 확인. 비어있으면 예외 발생 |
peek() | 큐의 첫 요소 확인. 비어있으면 null 반환 |
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
// 요소 추가
queue.offer("Apple");
queue.offer("Banana");
queue.offer("Cherry");
System.out.println("큐 상태: " + queue); // [Apple, Banana, Cherry]
// 첫 요소 확인
System.out.println("peek(): " + queue.peek()); // Apple
// 요소 제거
System.out.println("poll(): " + queue.poll()); // Apple
System.out.println("poll(): " + queue.poll()); // Banana
System.out.println("큐 상태: " + queue); // [Cherry]
}
}
작업 요청이 들어온 순서대로 처리할 때
소비자-생산자 패턴 구현 시
BFS(너비 우선 탐색) 알고리즘
프린터 대기열, 콜센터 처리 등 순차적 작업이 필요한 경우
import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(5);
pq.offer(1);
pq.offer(3);
while (!pq.isEmpty()) {
System.out.println(pq.poll()); // 1, 3, 5 (오름차순 정렬)
}
}
}