Queue
처음에 저장한 데이터를 가장 먼저 꺼내는 FIFO(First In First Out)구조로 되어있다.
boolean add(Object o) | 지정된 객체를 Queue에 추가 |
Object remove() | Queue에서 객체를 꺼내 반환 |
Object element() | 삭제없이 요소를 읽어온다 (peek()와 달리 Queue가 비었을때 예외 발생) |
boolean offer(Object o) | Queue에 객체를 저장 |
Object poll() | Queue에서 객체를 꺼내 반환 |
Object peek() | 삭제없이 요소를 읽어옴 |
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Queue q = new LinkedList(); // Queue인터페이스의 구현체인 LinkedList사용
q.offer("0");
q.offer("1");
q.offer("2");
while (!q.isEmpty()){
System.out.println(q.poll());
}
}
}
실행 결과
Deque(Double-Ended Queue)
Queue의 변형으로, 양쪽 끝에서 추가/삭제가 가능하다
덱은 스택과 큐를 하나로 합쳐놓은 것과 같으며, 스택과 큐에 사용할수 있다
Deque | Queue | Stack |
offerLast() | offer() | push() |
pollLast() | pop() | |
pollFirst() | poll() | |
peekFirst() | peek() | |
peekLast() | peek() |
Priority Queue
저장한 순서에 상관없이 우선순위가 높은 것부터 꺼내며, null은 저장할 수 없다. (예외발생)
저장공간으로 배열을 사용하며, 각 요소를 힙(heap)의 형태로 저장한다.
(힙은 이진트리의 한 종류로 가장 큰 값이나 가장 작은 값을 빠르게 찾을수 있다)
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Queue pq = new PriorityQueue();
pq.offer(3);
pq.offer(1);
pq.offer(5);
pq.offer(2);
pq.offer(4);
System.out.println(pq);
Object obj = null;
while ( (obj = pq.poll()) != null){
System.out.println(obj);
}
}
}
실행 결과
저장 순서와 상관없이 힙이라는 자료구조의 형태로 저장되며, 꺼낼때는 우선순위가 높은것(순자가 작을수록 높음)부터 꺼낸다.
728x90
'Language > Java' 카테고리의 다른 글
8.4 Collection Framework - Map 인터페이스 (0) | 2021.07.24 |
---|---|
8.3 Collection Framework - set 인터페이스 (0) | 2021.07.20 |
8.1 Collection Framework - List 인터페이스 (0) | 2021.07.20 |
7. 날짜, 시간 & 형식화 (0) | 2021.07.19 |
6.2 java.lang패키지 (String 클래스) (0) | 2021.07.15 |