PriorityQueue 예제

Posted by Breeze24
2020. 12. 28. 22:25 카테고리 없음

PriorityQueue는 요소 들 중에 우선순위가 높은 요소를 꺼내 주는 기능을 한다. 

우선순위는 생성자에서 지정할 수 있다.

 

PriorityQueue 예제

 

우선 순위가 낮은 순 - PriorityQueue<>();  

우선 순위가 높은 순 - PriorityQueue<>(Collections.reverseOrder()); 

 

public static void main(String[] args) {

Queue queue = new PriorityQueue();

queue.offer("z");

queue.offer("a");

queue.offer("c");

queue.offer("g");

queue.offer("q");

queue.offer("q");

queue.offer("b");

 

System.out.println(queue);

 

//출력 결과 : [a, g, b, z, q, q, c] a가 맨 앞으로 왔고, 뒤의 요소들은 동일하지 않다. 중복을 허용한다.

 

Object temp = null;

while ((temp = queue.poll())!=null) {

        System.out.println(temp);

     }

}

 

출력 결과