java.util.PriorityQueue
FIFO 구조를 가진 Queue에 우선순위가 포함된 자료구조
우선순위를 먼저 결정하고 우선순위가 높은 엘리먼트가 먼저 나감
데이터를 삽입할 때 우선순위를 기준으로 최대 힙 또는 최소 힙을 구성함
import java.util.Collections;
import java.util.PriorityQueue;
public class PriorityQueueExam {
public static void main(String[] args) {
// 우선순위 낮은 순
PriorityQueue<Integer> q1 = new PriorityQueue<>();
// 우선순위 높은 순
PriorityQueue<Integer> q2 = new PriorityQueue<>(Collections.reverseOrder());
}
}
// 값 추가
q1.add(1);
q1.offer(2);
q2.add(1);
q2.offer(2);
정상적으로 추가된 경우 true
, 아닌(큐가 가득찬) 경우 false
를 반환
추가할 수 없는 경우 IllegalStateException
을 발생
System.out.println("*** q1 poll");
System.out.println(q1.poll()); // 1
System.out.println(q1.poll()); // 2
System.out.println("*** q2 poll");
System.out.println(q2.poll()); // 2
System.out.println(q2.poll()); // 1
System.out.println("*** q1 peek");
System.out.println(q1.peek()); // 1
System.out.println(q1.peek()); // 1
System.out.println("*** q2 peek");
System.out.println(q2.peek()); // 2
System.out.println(q2.peek()); // 2
우선순위가 가장 높은 값을 반환하고 우선순위 큐에서 제거
우선순위가 가장 높은 값을 반환 (참조의 역할)