전공/객체지향프로그래밍

[객체지향프로그래밍][Java] Queue 심화 내용

Campus Coder 2023. 6. 1. 22:04
728x90
반응형

Interface Queue<E>

Queue는 인터페이스 Collection<E> 상속

메소드 기능
boolean add(E e) e를 큐에 삽입, 성공시 true 반환
용량을 초과한 경우 IllegalStateException 발생
E element() 큐의 head 반환
큐가 비어있으면 예외 발생
boolean offer(E e) e를 큐에 삽입, 성공시 true 반환
용량을 초과한 경우 false 반환
E peek() 큐의 head 검색
큐가 비어있으면 null반환
E poll() 큐의 head 검색 및 삭제
큐가 비어있으면 null 반환
E remove() 큐의 head 삭제
큐가 비어있으면 예외 발생

 

Queue는 선입선출 방식으로 원소를 저장

 

head에서는 remove, poll로 인해 삭제가 일어남

rear(head의 반대쪽)에서는 add, offer로 인해 삽입이 일어남

 

대부분의 경우 Queue에서 삽입이 성공적으로 이루어지지만

BlockingQueue 등 용량이 정해져있는 큐에서는 삽입 실패가 일어나기도 함

 

Queue에서는 일반적으로 null 삽입 불가

하지만 Queue를 상속받는 인터페이스 LinkedList에서는 null 삽입 가능

 

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.LinkedList;

public class Main {
    public static void main(String[] args) {
        Queue<String> q = new LinkedList<>();

        System.out.println(q.offer("Apple"));
        System.out.println(q.offer(null));
        // LinkedList에서는 null 삽입 가능
        System.out.println(q.offer("Mango"));
        while (!q.isEmpty()) {
            System.out.println("examine: " + q.peek());
            System.out.println("remove: " + q.poll());
        }

        q = new LinkedBlockingQueue<>(2);

        System.out.println(q.offer("Apple"));
        System.out.println(q.offer("Orange"));
        // 일반적으로 null 삽입 불가
        System.out.println(q.offer("Mango"));
        for (int i = 0; i < 3; i++) {
            System.out.println("examine: " + q.peek());
            System.out.println("remove: " + q.poll());
        }
    }
}
true
true
true
examine: Apple
remove: Apple
examine: null
remove: null
examine: Mango
remove: Mango
true
true
false
examine: Apple
remove: Apple
examine: Orange
remove: Orange
examine: null
remove: null
728x90
반응형