Java & Algorithm/Java
[JAVA] 기초문법 - 자료구조 컬렉션 Stack 생성과 메서드 기능 이용 연습 - 23
ohnyong
2023. 7. 27. 20:25
Collection - Stack
바구니, 쌓인다, Stack 자료구조에 대해 복습해보고자 한다.
- 자료를 넣으면 하나씩 쌓인다, 자료를 빼면 맨 마지막에 덮힌것이 빠진다 Last In First Out
- 사용하는 이유? 최근 저장된 데이터를 나열하고 싶을때, 데이터의 중복처리를 막고 싶을때.
- Method
- .push()
- .peek()
- .pop()
- 항상 공식 문서를 확인하고 정확한 명칭을 기억하려 노력하자
- 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
1. 기본 생성법
Stack<E> name = new Stack<E>();
//Stack 선언 + (객체)생성 Stack<Integer> intStack = new Stack<Integer>();
2. Stack 메서드 사용
.push(E item) : item 추가(쌓기)abc
//추가 //push(E item) 메서드로 생성한 Linked List에 item을 넣어보자. intStack.push(10); intStack.push(15); intStack.push(1);
.peek() : 맨 위 쌓인 item 읽기
//읽기 //peek() 메서드로 Stack의 item을 읽을 수 있다. //10 -> 15 -> 1 순서로 들어갔기 때문에, 맨 위에는 1이있다. 그래서 1이 나온다. basket같이 들어가기 때문에. System.out.println(intStack.peek());
.pop() : 맨 위에 쌓인 item 제거하며 반환
//pop()은 가장 위 item을 특이하게 말그대로 꺼내면서 제거 한다. //ex) 1 2 3 이 차례대로 있는 Stack의 경우 peek를 하면 1 2 3 이 그대로 있지만 pop을 하면 1 2 만 남게된다. //pop() 메서드로 Stack의 가장 위 item을 제거하면서 value를 반환한다. while(!intStack.isEmpty()){ System.out.println(intStack.pop());