본문 바로가기

Java/문법

17 - 5장 Stack<E> 컬렉션 클래스

1. Stack<E> 컬렉션의 특징

 

- Stack<E>는 클래스이므로 자체적으로 객체 생성 가능

- List<E> 컬렉션의 구현 클래스인 Vector<E> 클래스의 자식 클래스

- 후입선출(LIFO:last in first out) 자료구조

- 나중에 입력된 데이터가 먼저 출력되는 것

- Vector<E>의 모든 기능 포함

 

2.Stack<E>의 주요 메서드

 

- Stack 메서드를 사용하려면 변수를 Stack<E> 타입으로 선언

- Stack<E> 컬렉션에 E1,E2,E3,E4의 순으로 데이터를 추가 

- 데이터를 꺼내는 순서는 E4,E3,E2,E1

구분 메서드명 기능
데이터 추가 push(E item) 매개변수인 item을 Stack<E>에 추가
데이터 확인 peek() 가장 상위에 있는 원솟값 리턴(데이터는 변화 없음)
데이터 위치 검색 search(Object o) Stack<E> 원소의 위칫값을 리턴
(맨 위의 값이 1, 아래로 내려갈수록 1씩 증가)
데이터 추출 pop() 최상위 데이터 꺼내기(데이터의 개수 감소)
empty 여부 검사 empty() Stack<E> 객체가 비어 있는지 여부를 리턴

 

package CollectionFramework;

import java.util.Stack;

public class StackMethod {
	public static void main(String[] args) {
		Stack<Integer> stack = new Stack<Integer>();
		//1.E push(E element)
		stack.push(2);
		stack.push(5);
		stack.push(3);
		stack.push(7);
		
		//2.E peek()
		System.out.println(stack.peek());
		System.out.println(stack.size());
		System.out.println();
		
		//3.search(Object o)
		System.out.println(stack.search(7));
		System.out.println(stack.search(3));
		System.out.println(stack.search(5));
		System.out.println(stack.search(2));
		System.out.println(stack.search(9));
		System.out.println();
		
		//4.E pop()
		System.out.println(stack.pop());
		System.out.println(stack.pop());
		System.out.println(stack.pop());
		System.out.println(stack.pop());
		System.out.println();
		
		//5.boolean empty()
		System.out.println(stack.empty());
	}
}