본문 바로가기
> JAVA

[JAVA][Interface] Queue<E>

by bky373 2020. 11. 3.

 

Queue<E>

너무너무 많이 들어본 Queue이다! 클래스인 줄 알았는데 자바에서는 인터페이스로 사용한다.
어떤 내용을 설명하고 있는지 Oracle docs 12 문서를 살펴보자

급하다면 빠르게 아래 요약 부분만 참고하자!

 


*** 요약 ***

Queue<E>는 무언가를 실행하기 전, 원소들을 보관하는 *컬렉션이다.
이 장소에서는 대개 **FIFO 방식으로 원소들을 정렬한다.

그리고 대표적인 메소드로는 add, offer / remove, poll/ element, peek 등이 있다.

*컬렉션: 일종의 틀, 그 중 큐는 입력값이 계속 뒤에서 채워지는 틀이다. 
** FIFO 방식은 First In First Out, 즉 선입선출 방식으로 먼저 들어온 원소가 먼저 나가는 방식을 말한다.



아래부터는
Queue 인터페이스의 속성과 특징,
또 메소드까지 전부 살펴보려 한다.

Package java.util

Interface Queue<E>

public interfaceQueue<E>extendsCollection<E>

A collection designed for holding elements prior to processing.
> 처리 전 원소들을 보관하기 위해 설계된 컬렉션이다.

Besides basicCollectionoperations, queues provide additional insertion, extraction, and inspection operations.
> 기본적인 Collection 작업 외에도 추가 삽입, 추출, 그리고 검사 작업을 제공한다.


Each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a special value (either null or false, depending on the operation).
> 각 메소드는 두 가지 양식으로 존재한다. : 하나는 작업이 실패하면 예외를 던지고, 다른 하나는 특수한 값(작업에 따라 null 또는 false)을 반환한다.


The latter form of the insert operation is designed specifically for use with capacity-restricted Queue implementations; in most implementations, insert operations cannot fail. 
> 삽입에서 후자의 경우, 용량이 제한된 Queue의 구현과 함께 사용하도록 특별히 설계되었다. 대부분의 구현에서 삽입 작업은 실패할 수 없다.

 

Throws exception

예외 발생

Returns special

특수한 값 반환

Insert

add(e)

offer(e)

Remove

remove()

poll()

Examine

element()

peek()

 

Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner.
> Queue는 일반적으로(반드시 그런 것은 아니지만) FIFO(선입선출) 방식으로 원소들을 정렬한다.

Among the exceptions are priority queues, which order elements according to a supplied comparator, or the elements' natural ordering, and LIFO queues (or stacks) which order the elements LIFO (last-in-first-out).
> 그 예외로 우선순위 큐가 있고, comparator에 따라 원소를 정렬한다. 그리고 LIFO 큐(혹은 스택)도 있는데, 이는 LIFO 방법(나중에 들어온 원소가 먼저 나가는 방법)으로 원소들을 정렬한다.


Whatever the ordering used, the
headof the queue is that element which would be removed by a call toremove()orpoll().
> 어떤 정렬이든 간에, remove() 또는 poll()이 실행될 때 큐의 head(머리)가 제거된다.


In a FIFO queue, all new elements are inserted at the
tail of the queue.
> FIFO방식의 큐에서는 모든 새로운 원소가 큐의 tail(꼬리)에 삽입된다.


Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties.
> 다른 종류의 큐에서는 다른 규칙을 사용할 수 있다. 모든 Queue는 반드시 자신만의 정렬 속성을 지정해야 한다.


The
offermethod inserts an element if possible, otherwise returning false.
> offer 메소드는 가능한 경우에 원소를 삽입하고, 그렇지 않으면(용량이 꽉 차있으면) false를 반환한다.


This differs from the
Collection.addmethod, which can fail to add an element only by throwing an unchecked exception.
> 이는 Collection.add 메소드와 차이가 있는데, add는 false 대신 unchecked 예외를 발생시키며 (원소)추가에 실패한다.(offer는 예외를 발생시키지 않는다.)

 

** offer() 메소드와 add() 메소드의 차이

- offer 메소드: 요소를 큐에 추가하려고 시도하고 요소가 추가 될 수없는 경우(큐가 꽉 찬 경우) false를
반환하고 요소가 추가되면 true를 반환하고 특정예외를 throw하지 않는다.

- add 메소드: 큐에 요소를 추가하려고 시도하고 요소가 이미 큐에 있으면 false를 반환하고 요소가
추가되면 true를 반환하고 큐가 가득 차면 예외를 throw한다.(출처 :https://code-examples.net/ko/q/294270)

 


The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues.
> 다시 말해 offer 메소드는 고정된 용량을 가진(or 바운드 된) 큐와 같이 *실패가 정상적인 경우에 사용하도록 설계되었다. (*용량이 꽉찬 큐에 원소를 추가했을 때 에러를 발생시키지 않고 이실패를 정상적으로 보고 false를 반환한다는 의미)

 

There move() and poll() methods remove and return the head of the queue.
> remove()와 poll() 메소드는 큐의 head를 제거하고 반환한다.

Exactly which element is removed from the queue is a function of the queue's ordering policy, which differs from implementation to implementation.
> 정확히 어떤 원소가 제거되는지는 큐의 정렬 정책에 따라 다르다.


The remove() and poll() methods differ only in their behavior when the queue is empty: the remove() method throws an exception, while the poll() method returns null.
> remove()와 poll() 메소드는 큐가 비어있을 때만 다르게 작동한다. 전자는 예외를 발생시키고, 후자는 null을 반환한다.


The
element()andpeek()methods return, but do not remove, the head of the queue.
> element() 와 peek() 메소드는 큐의 헤드 반환은 하지만 제거하지는 않는다.


The Queue interface does not define the
blocking queue methods, which are common in concurrent programming.
> 큐 인터페이스는 동시작업 프로그래밍에서 흔한 blocking queue 메소드에 대해선 정의하지 않는다.


These methods, which wait for elements to appear or for space to become available, are defined in the
BlockingQueueinterface, which extends this interface.
> 원소가 나타나거나 혹은 공간이 확보될 때까지 기다리는 이들 메소드는 BlockingQueue 에서 정의되어 이 인터페이스를 확장한다.


Queue implementations generally do not allow insertion of null elements, although some implementations, such as
LinkedList, do not prohibit insertion of null.
> Queue는 LinkedList와 같은 구현과 다르게 일반적으로 null 삽입을 허용하지 않는다.


Even in the implementations that permit it, null should not be inserted into a Queue, as null is also used as a special return value by the poll method to indicate that the queue contains no elements.
> 그걸 허용하는 구현이라 하더라도 null은 Queue에 삽입되어선 안 된다. 왜내하면 null은 큐 안에 원소가 없을 때 poll 메소드가 사용하는 특수한 값이기 때문이다.


Queue implementations generally do not define element-based versions of methods the
equalsandhashCodebut instead inherit the identity based versions from class Object,
> Queue는 일반적으로 equals와 hasCode 메소드의 원소기반 버전을 정의하진 않고, 대신 클래스 객체의 신원기반 버전을 정의한다.


because element-based equality is not always well-defined for queues with the same elements but different ordering properties.
> 왜냐하면 원소기반의 평등은같은 원소를 가졌지만 다른 정렬 속성을 가진큐에서 항상 명확하게 정의되어 있지 않기 때문이다.


This interface is a member of the
Java Collections Framework.
> 이 인터페이스는 자바 컬렉션 프레임워크의 멤버이다.

 

Method Summary

Modifier and Type

Method

Description

boolean

add​(E e)

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.

E

element()

Retrieves, but does not remove, the head of this queue.

boolean

offer​(E e)

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.

E

peek()

Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

E

poll()

Retrieves and removes the head of this queue, or returns null if this queue is empty.

E

remove()

Retrieves and removes the head of this queue.

 


참고 : Deque대해
https://blog.naver.com/bo373/221648558709

 

 

출처 : https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Queue.html

Queue (Java SE 12 & JDK 12 )

 

 

댓글