Java - Queue 인터페이스 및 관련 클래스

Queue 인터페이스

Queue 인터페이스는 J2SE 5.0에서 추가된 인터페이스로써 First-In, First-Out 형태를 가지고 있는 Queue 데이터 구조를 가진다. Queue 인터페이스는 저장된 데이터의 첫 번째 데이터만 삭제할 수 있다. 다른 인터페이스와는 달리 데이터를 저장하기 위해서는 offer(), 삭제를 하기 위해서는 remove(), 데이터를 얻기 위해서는 element(), peek(), poll() 등의 메소드를 가지고 있다. Queue 인터페이스를 구현한 하위 클래스로는 LinkedList, PriorityQueue가 있다.

Queue 메소드

메소드 설명
boolean add(E e) Queue(큐)에 객체를 넣고, 성공하면 true를 반환한다.
boolean offer(E e) Queue(큐)에 객체를 넣는다.
E poll() Queue(큐)에서 객체를 반환하고, 비어 있다면 null을 반환한다.
E peek() Queue(큐)의 맨 아래 있는 객체를 반환하고, 객체를 큐에서 제거하진 않는다.
E remove() Queue(큐)의 맨 아래 있는 객체를 반환하고, 객체를 큐에서 제거한다.

PriorityQueue

PriorityQueue 예제

package com.devkuma.tutorial.java.util.collection;

import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;

public class PriorityQueueClass {

    public static void main(String[] args) {

        Queue<String> queue = new PriorityQueue<String>();
        queue.add("a");
        queue.add("b");
        queue.add("c");
        queue.add("d");
        queue.add("e");
        System.out.println("head element: " + queue.element());
        System.out.println("head peek : " + queue.peek());

        System.out.println("iterating the queue elements:");
        Iterator<String> itr = queue.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }

        System.out.println("head remove : " + queue.remove());
        System.out.println("head poll : " + queue.poll());

        System.out.println("after removing two elements:");
        Iterator<String> itr2 = queue.iterator();
        while (itr2.hasNext()) {
            System.out.println(itr2.next());
        }
    }
}

실행 결과는 아래와 같다.

head element: a
head peek : a
iterating the queue elements:
a
b
c
d
e
head remove : a
head poll : b
after removing two elements:
c
d
e