본문 바로가기
Programming/Java

[Java] 자바 Stack(스택) 클래스

by 서현 SEOHYEON 2022. 12. 19.

💚 import

import java.util.Stack;

 

💚 생성자

Stack() 빈 스택을 생성한다

 

 

💚 메서드

반환형 메서드 설명
boolean empty() 스택이 비어있는지 확인
E peek() 스택의 맨 위에 있는 객체를 확인(제거X)
E pop() 스택의 맨 위에 있는 객체를 제거하고 반환
E push(E item) 스택의 맨 위에 데이터를 삽입
int search(Object o) 스택에서 객체의 위치를 반환
- 위에서 부터의 거리
- 맨 위가 1, 그 밑이 2, ...
int size() 요소의 개수를 반환

 

 

💚 사용 예제

Stack<Integer> stack = new Stack<>();

//현재 상태: 비어있음
if(stack.empty()){
    System.out.println("현재 스택이 비어있습니다.");
}

stack.push(3);
stack.push(2);
stack.push(4);
stack.push(5);
stack.push(1);

//현재 상태: 3 2 4 5 1
System.out.println("현재 맨 위에 있는 데이터: " + stack.peek());
System.out.println(stack.pop() + " 데이터를 제거했습니다.");

//현재 상태: 3 2 4 5
System.out.println("현재 맨 위에 있는 데이터: " + stack.peek());
System.out.println(stack.pop() + " 데이터를 제거했습니다.");

//현재 상태: 3 2 4
System.out.println("4는 위에서부터 " + stack.search(4) + "번째에 위치");
System.out.println("2는 위에서부터 " + stack.search(2) + "번째에 위치");
System.out.println("3는 위에서부터 " + stack.search(3) + "번째에 위치");

 

- 실행 결과

현재 스택이 비어있습니다.
현재 맨 위에 있는 데이터: 1
1 데이터를 제거했습니다.
현재 맨 위에 있는 데이터: 5
5 데이터를 제거했습니다.
4는 위에서부터 1번째에 위치
2는 위에서부터 2번째에 위치
3는 위에서부터 3번째에 위치

공식 문서

https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html

 

Stack (Java Platform SE 8 )

The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item o

docs.oracle.com

 

댓글