💚 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
'Programming > Java' 카테고리의 다른 글
[Java] 자바 LinkedList 클래스 (0) | 2023.01.09 |
---|---|
[Java] 자바 ArrayList 클래스 (0) | 2023.01.04 |
[Java] 문자열 관련 메서드 - charAt(), length() (0) | 2022.12.16 |
[Java] 자바 자주쓰는 형 변환 (0) | 2022.11.29 |
[Java] 자바 빠른 입출력(BufferedReader, BufferedWriter) (0) | 2022.11.14 |
댓글