์๋ฐ์์ ํ(Queue)๋ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ๊ณ ์ฒ๋ฆฌํ๋ ์๋ฃ ๊ตฌ์กฐ๋ก, ์ผ๋ฐ์ ์ผ๋ก FIFO (First In, First Out) ๋ฐฉ์์ผ๋ก ์๋ํ๋ค. ํ๋ฅผ ๊ตฌํํ๊ธฐ ์ํด ์๋ฐ์์๋ Queue ์ธํฐํ์ด์ค์ ๊ทธ ๊ตฌํ์ฒด์ธ LinkedList, PriorityQueue, ArrayDeque ๋ฑ์ ์ฌ์ฉํ๋ค.
import java.util.Queue;
import java.util.LinkedList;
public class QueueExample {
public static void main(String[] args) {
// ํ ์์ฑ
Queue<String> queue = new LinkedList<>();
// ํ์ ์์ ์ถ๊ฐ (offer ๋ฉ์๋ ์ฌ์ฉ)
queue.offer("Apple");
queue.offer("Banana");
queue.offer("Cherry");
// ํ์์ ์์ ์ ๊ฑฐ (poll ๋ฉ์๋ ์ฌ์ฉ)
System.out.println("Removed: " + queue.poll()); // Apple
System.out.println("Removed: " + queue.poll()); // Banana
// ํ์์ ์ฒซ ๋ฒ์งธ ์์ ํ์ธ (peek ๋ฉ์๋ ์ฌ์ฉ)
System.out.println("Next in queue: " + queue.peek()); // Cherry
// ํ๊ฐ ๋น์๋์ง ํ์ธ
System.out.println("Is the queue empty? " + queue.isEmpty()); // false
}
}
์ด ์์์์ LinkedList๋ Queue ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ ๋ํ์ ์ธ ํด๋์ค์ด๋ค. ํ์ ์์ชฝ์์ ์ฝ์ ๊ณผ ์ญ์ ๊ฐ ๋น ๋ฅด๊ธฐ ๋๋ฌธ์, ๋๊ธฐ์ด์ด๋ ์์ ๊ด๋ฆฌ ๋ฑ ๋ค์ํ ์๋๋ฆฌ์ค์์ ์ ์ฉํ๊ฒ ์ฌ์ฉ๋๋ค.