자바 큐
-
Java) Java-collection queue2022.11.15
Java) Java-collection queue
2022. 11. 15. 13:42
queue = FIFO (First-In-First-out) 구조
Enqueue = 큐 맨뒤에 데이터가 추가된다.
Dequeue = 큐 맨앞에 데이터가 삭제된다.
java에서 queue를 구현하기위해서는 LinkedList를 사용해 구현한다.
return | Method |
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.
|
add와 offer은 queue에 값을 추가해준다는것은 동일하지만 add는 큐가 꽉차 더이상 값을 추가할수없을때 예외를 발생시키지만 offer는 추가실패를 의미하기위해 false를 return한다.
poll() 과 remove도 마찬가지이다. poll()은 더이상 뺄 값이없을때 null을 return하지만 remove는 예외를 발생시킨다. (아래예시)
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) throws IOException {
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(1);
queue.offer(2);
System.out.println(queue.remove());
System.out.println(queue.remove());
System.out.println(queue.poll()); // null 리턴
System.out.println(queue.remove()); // 예외발생
}
}
peek() = 가장 앞에있는 값을 가리킨다. 이때도 peek()은 queue가 비어있으면 null 리턴
element() = queue가 비어있으면 예외 발생
public class Main {
public static void main(String[] args) throws IOException {
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(1);
queue.offer(2);
System.out.println(queue.peek()); // -> 1
System.out.println(queue.element()); // -> 1
}
}
public class Main {
public static void main(String[] args) throws IOException {
Queue<Integer> queue = new LinkedList<Integer>();
System.out.println(queue.peek());
System.out.println(queue.element());
}
}