제로베이스의 자료구조 과제 중 큐와 관련된 문제가 나와 공부하면서 내용을 정리해본다.

| 메서드 | 설 명 |
|---|---|
| boolean add(Object o) | 지정된 객체를 Queue에 추가한다. 성공하면 true 반환. 저장공간이 부족하면 IllegalStateException 발생한다. |
| Object remove() | Queue에서 객체를 꺼내 반환한다. 비어있으면 NoSuchElementException 발생한다. |
| Object element() | 삭제없이 요소를 읽어온다. peek 와 달리 Queue 가 비었을 때 NoSuchElementException 발생한다. |
| boolean offer(Object o) | Queue에 객체를 저장한다. 성공하면 true 실패하면 false 를 반환한다. |
| Object poll() | Queue에서 객체를 꺼내서 반환한다. 비어있으면 null 을 반환한다. (예외가 발생하지 않는다.) |
| Object peek() | 삭제없이 요소를 읽어 온다. Queue가 비어있으면 null 을 반환한다. |
Queue g = new LinkedList();
g.offer("o");
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static Queue q = new LinkedList();
static final int MAX_SIZE = 5; // Queue에 최대 5개까지만 저장되도록 한다.
public static void main(String[] args) {
System.out.println("help를 입력하면 도움말을 볼 수 있습니다.");
while (true) {
System.out.print(">> ");
try{
// 화면으로부터 라인단위로 입력받는다.
Scanner sc = new Scanner(System.in);
String input = sc.nextLine().trim();
if("".equals(input)) continue;
if(input.equalsIgnoreCase("q")){ // 대소문자를 구분하지 않고 비교
System.exit(0);
} else if(input.equalsIgnoreCase("help")){
System.out.println(" help - 도움말을 보여줍니다.");
System.out.println(" q 또는 Q - 프로그램을 종료합니다.");
System.out.println(" history - 최근에 입력한 명령어를 " + MAX_SIZE + "개 보여줍니다.");
} else if(input.equalsIgnoreCase("history")){
save(input); // 입력받은 명령어를 저장한다.
LinkedList list = (LinkedList) q; // LinkedList의 내용을 보여준다.
for (int i = 0; i < list.size(); i++) {
System.out.println((i + 1) + "." + list.get(i));
}
} else {
save(input);
System.out.println(input);
} // if(input.equalsIgnoreCase("q")) {
} catch (Exception e){
System.out.println("입력오류 입니다.");
}
}
}
public static void save(String input){
if(!"".equals(input)) // input이 공백이 아니면
q.offer(input); // Queue에 저장
if(q.size() > MAX_SIZE) // Queue의 최대 크기를 넘으면
q.remove(); // 제일 처음 입력된 데이터 삭제
}
}