[Java 26] 자바 - 컬렉션 프레임워크(2)

학습목표

  1. Stack과 Queue에 대해 이해한다.

후입선출(LIFO: Last In First Out)과 선입선출(FIFO : First In First Out) 컬렉션

컬렉션

STACK과 QUEUE 모두 배열의 빈공간이 없게 데이터를 저장하기 위한 자료구조입니다.

기본 용어

구분 입력 삭제
stack push( ) pop( )
queue put( ) get( )

Overflow

Underflow

Stack

기본 생성자

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


주요 메소드

리턴타입 메소드 설명
E puch(E item) 주어진 객체를 스택에 넣는다
E peek() 스택의 맨 위 객체를 가져온다. 객체를 스택에서 제거하지 않는다
E pop() 스택의 맨 위 객체를 가져온다. 객체를 스택에서 제거한다.


예제 1

public class StackExample {
public static void main(String[] args) {
	Stack<Coin> coinBox = new Stack<Coin>();

	//동전 끼움
	coinBox.push(new Coin(100));
	coinBox.push(new Coin(50));
	coinBox.push(new Coin(500));
	coinBox.push(new Coin(10));

	while (!coinBox.isEmpty()) {	//동전케이스 비었는지 확인
		Coin coin = coinBox.pop();	//동전케이스 제일 위의 동전 꺼내기
		System.out.println("꺼내온 동전 : " + coin.getValue() + "원");
	}
}
}


Queue

기본 생성자

Queue<E> queue = new LinkedLsit<E>();


주요 메소드

리턴타입 메소드 설명
boolean offer(E e) 주어진 객체를 큐에 넣는다
E peek() 스택의 맨 위 객체를 가져온다. 객체를 큐에서 제거하지 않는다
E poll() 스택의 맨 위 객체를 가져온다. 객체를 큐에서 제거한다.


예제 1

public class Message {
	public String command;
	public String to;
	
	public Message(String command, String to) {
		this.command = command;
		this.to = to;
	}
}
public class QueueExample {
public static void main(String[] args) {
	Queue<Message> messageQueue = new LinkedList<Message>();

	messageQueue.offer(new Message("sendMail", "홍길동"));
	messageQueue.offer(new Message("sendSMS", "김길동"));
	messageQueue.offer(new Message("sendKakaotalk", "강길동"));

	while (!messageQueue.isEmpty()) {
		Message message = messageQueue.poll();
		switch (message.command) {
		case "sendMail":
			System.out.println(message.to + "님에게 메일을 보냅니다.");
			break;
		case "sendSMS":
			System.out.println(message.to + "님에게 SMS를 보냅니다.");
			break;
		case "sendKakaotalk":
			System.out.println(message.to + "님에게 카카오톡을 보냅니다.");
			break;
		}
	}
}
}

태그:

카테고리:

업데이트:

댓글남기기