정의
과자로 생각하면 프링글스로 생각하면 되는데 가장 나중에 넣은 칩 조각을 가장 먼저 먹게 되는 것.

가장 많이 사용되는 곳은
| 메서드 | 설명 |
|---|---|
| stack.push(1); | 스택에 값 1 추가 성공시 return data |
| stack.size(); | 스택의 크기 출력 |
| stack.empty(); | 스택이 비어 있으면 true, 비어 있지 않으면 false를 반환 Stack 클래스에만 정의 |
| stack.peek(); | 스택의 제일 상단에 있는(마지막으로 저장된) 요소를 반환 성공시 return Data 만약 Stack이 비어있을 경우 throw EmptyStackException |
| stack.pop(); | 스택의 제일 상단에 있는(마지막으로 저장된) 요소를 반환후, 해당 요소를 스택에서 제거함. (값을 remove 할때 pop 을 사용하면된다.) 비어있을 경우 throw EmptyStackException |
| stack.search(1); | 스택에서 전달된 객체가 존재하는 위치의 인덱스를 반환 이때 인덱스는 제일 상단에 있는(마지막으로 저장된) 요소의 위치부터 0이 아닌 1부터 시작함. 값이 없으면 -1 반환 |
| stack.contains(1); | 스택에 1이 있으면 true, 없으면 false 를 반환 |
| stack.add(1) | 스택에 값 1 추가 push와 다르게 add는 true/false를 반환 |
| stack.clear() | 스택안에 모든 값 제거 |
| stack.isEmpty() | 스택이 비어있으면 true, 비어있지 않으면 false를 반환 Collection인터페이스에 정의 |
Stack<Integer> stackInt = new Stack<>(); // Integer Stack선언, 뒤의 타입 생략 가능
Stack<String> stackStr = new Stack<>(); // String Stack선언
Stack<Boolean> stackBool = new Stack<>(); // Boolean Stack선언
// 값 추가 push()stackInt.push(1);
stackInt.push(2);
stackInt.push(3);
System.out.println(stackInt);
// 1 -> 3 순으로 추가
System.out.println(stackInt.peek());
System.out.println(stackInt.pop());
System.out.println(stackInt);
// 값 추가 add()stackInt.add(1);
stackInt.add(2);
stackInt.add(3);
// 1- > 3 순으로 추가
stackInt.clear();
System.out.println(stackInt.empty());
stackInt.push(1);
System.out.println(stackInt.empty());
stackInt.clear();
stackInt.push(1);
stackInt.push(2);
stackInt.push(3);
stackInt.push(4);
// [1, 2, 3, 4]
System.out.println(stackInt.search(2));
System.out.println(stackInt.search(4));
System.out.println(stackInt.search(1));
Stack<Integer> stk = new Stack<Integer>();
int tmp = 0;
for (int i = 1 ; i <= 5 ; i++){
stk.push(i);
}
System.out.println("stk = " + stk);
for (int i = 1 ; i <= 5 ; i++){
tmp = stk.peek();
System.out.println("stk.pop = " + stk.pop()); // 첫 번째 값 삭제 및 출력
}
for (int i = 1 ; i <= 5 ; i++){
stk.push(i);
}
System.out.println("stk = " + stk);
stk.push(stk.pop());
System.out.println("stk = " + stk);
stk = [1, 2, 3, 4, 5]
stk.pop = 5
stk.pop = 5
stk.pop = 5
stk.pop = 5
stk.pop = 5
---------------------------------------
stk = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
stk = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]