💚 큐(Queue)
- 스택과 다르게 큐는 클래스가 아닌 "인터페이스"로 작성되어 있다.
- 알려진 구현 클래스들
AbstractQueue, ArrayBlockingQueue, ArrayDeque, ConcurrentLinkedDeque, ConcurrentLinkedQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, LinkedList, LinkedTransferQueue, PriorityBlockingQueue, PriorityQueue, SynchronousQueue
💚 import
import java.util.Queue;
💚 메서드
반환형 | 메서드 | 설명 |
boolean | add(E e) | 큐에 지정된 요소 삽입 |
E | element() | 이 큐의 맨 앞의 값을 검색(제거X) |
boolean | offer(E e) | 큐에 지정된 요소 삽입 |
E | peek() | 이 큐의 맨 앞의 값을 검색(제거X), 큐가 비어있으면 null 반환 |
E | poll() | 이 큐의 맨 앞을 제거, 큐가 비어있으면 null 반환 |
E | remove() | 이 큐의 맨 앞을 제거 |
- add와 offer의 차이
큐가 꽉 찬 경우 add는 예외를 발생시킴. offer는 false를 반환
- 각 메서드는 두 가지 형태로 존재. 하나는 작업이 실패할 경우 예외를 던지고, 다른 하나는 특수 값(null or false)을 반환
예외 발생 | 특정한 값 반환 | |
삽입 | add(e) | offer(e) |
제거 | remove() | poll() |
검사 | element() | peek() |
💚 사용 예제
- LinkedList를 사용하여 구현함
import java.util.LinkedList;
import java.util.Queue;
public class QueueTest {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.add("Red");
queue.add("Orange");
queue.add("Yellow");
queue.add("Green");
System.out.println(queue);
//[Red, Orange, Yellow, Green]
String str1 = queue.poll();
String str2 = queue.poll();
System.out.println("str1 = " + str1);
System.out.println("str2 = " + str2);
//str1 = Red
//str2 = Orange
System.out.println(queue.peek());
//Yellow
}
}
공식 문서
https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html
Queue (Java Platform SE 8 )
A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations. Each of these methods exists in two forms: one throws an exception if the opera
docs.oracle.com
'Programming > Java' 카테고리의 다른 글
[Java] 자바 switch 문 (0) | 2023.01.26 |
---|---|
[Java] 소수점 반올림, 소수점 원하는 자리까지 출력 (0) | 2023.01.13 |
[Java] 자바 LinkedList 클래스 (0) | 2023.01.09 |
[Java] 자바 ArrayList 클래스 (0) | 2023.01.04 |
[Java] 자바 Stack(스택) 클래스 (0) | 2022.12.19 |
댓글