공식문서
Stack 특징
Stack 클래스 주요 메소드 정리
메소드 설명 push(E item)
스택의 맨 위에 요소를 추가합니다. pop()
스택의 맨 위에 있는 요소를 제거하고 반환합니다. peek()
스택의 맨 위에 있는 요소를 제거하지 않고 반환합니다. isEmpty()
스택이 비어 있는지 여부를 확인하여 true
또는false
를 반환합니다.search(Object o)
특정 요소가 스택에서 위치하는 위치(1부터 시작)를 반환하며, 없을 경우 -1
을 반환합니다.size()
스택에 있는 요소의 개수를 반환합니다. clear()
스택의 모든 요소를 제거하여 비웁니다.
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
// Stack 객체 생성
Stack<Integer> stack = new Stack<>();
// 스택에 요소 추가 (push 메소드)
stack.push(10);
stack.push(20);
stack.push(30);
// 스택의 현재 상태 출력
System.out.println("스택: " + stack);
// 스택의 맨 위 요소 확인 (peek 메소드)
System.out.println("스택의 맨 위 요소: " + stack.peek());
// 스택에서 요소 제거 (pop 메소드)
int removedElement = stack.pop();
System.out.println("제거된 요소: " + removedElement);
System.out.println("스택 (pop 후): " + stack);
// 특정 요소의 위치 찾기 (search 메소드, 1부터 시작)
int position = stack.search(10);
if (position != -1) {
System.out.println("10은 스택의 " + position + "번째 위치에 있습니다.");
} else {
System.out.println("10은 스택에 없습니다.");
}
// 스택이 비었는지 확인 (empty 메소드)
System.out.println("스택이 비어 있는가? " + stack.empty());
// 모든 요소 제거 후 empty 상태 확인
stack.pop(); // 남은 요소 제거
System.out.println("스택이 비어 있는가? " + stack.empty());
}
}
##실행결과
스택: [10, 20, 30]
스택의 맨 위 요소: 30
제거된 요소: 30
스택 (pop 후): [10, 20]
10은 스택의 1번째 위치에 있습니다.
스택이 비어 있는가? false
스택이 비어 있는가? true