한 쪽 끝에서는 삽입이, 다른 쪽 끝에서는 삭제가 일어나는 구조
메서드 | 설명 |
---|---|
boolean add(E e) | Queue에 요소 e 추가 |
E element() | Queue의 제일 상단 요소 반환 |
E remove() | Queue의 최상단 요소를 반환 후 제거 |
boolean offer(E e) | Queue에 요소 e를 추가 |
E peek() | Queue의 제일 상단 요소 반환 |
E poll() | Queue의 최상단 요소를 반환 후 제거 |
→ Queue는 인터페이스이므로, 사용하려면 업캐스팅이 필요하다.
public static void main(String[] args) {
Queue<String> q = new LinkedList<>();
//1. add: rear위치에 e 삽입
q.add("apple");
q.add("banana");
q.add("cherry");
q.add("tomato");
System.out.println(q);
//2. element: front에 위치한 데이터 반환
System.out.println("element: "+q.element());
//3. remove:front에 위치한 데이터를 반환 후 삭제
System.out.println("remove: "+q.remove());
System.out.println(q);
//4. offer(e): rear위치에 데이터 삽입
q.offer("peach");
System.out.println("offer: "+q);
//5. peek(): front 위치에 있는 데이터의 값 반환
System.out.println("peek: "+q.peek());
//6. poll(): front 위치에 있는 데이터를 반환 후 삭제
System.out.println("poll: "+q.poll());
System.out.println(q);
}
}
한 쪽 끝에서 삽입과 삭제가 모두 일어나는 구조
메서드 | 설명 |
---|---|
E peek() | top 요소를 반환 |
E pop() | top 요소 제거 후 반환 |
E push(E item) | top에 요소 추가 |
int search(Object O) | 요소 O가 있는지 검색해서 위치 반환 |
→ Stack은 클래스이므로, 바로 사용 가능
public static void main(String[] args) {
Stack<String> s = new Stack<String>();
//1. push():데이터 삽입
s.push("apple");
s.push("banana");
s.push("cherry");
System.out.println(s);
//2. pop(): top의 데이터 삭제
System.out.println("pop: "+s.pop());
System.out.println(s);
//3. peek(): top의 데이터 보기
System.out.println("peek: " + s.peek());
//4. search() : 첫 번째가 0이 아니고 1임
System.out.println(s.search("apple"));
System.out.println(s.search("banana"));
}
}