Language/JAVA

[JAVA] LIFO와 FIFO 컬렉션

IT수정 2024. 10. 18. 11:06

LIFO와 FIFO 컬렉션

후입선출(LIFO)은 나중에 넣은 객체가 먼저 빠져나가고, 선입선출(FIFO)은 먼저 넣은 객체가 먼저 빠져나가는 구조를 말한다. 컬렉션 프레임워크는 LIFO 자료구조를 제공하는 스택 클래스와 FIFO 자료구조를 제공하는 큐 인터페이스를 제공하고 있다.

 

Stack

Stack 클래스는 LIFO 자료구조를 구현한 클래스이다. 다음은 Stack 객체를 생성하는 방법이다.

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

 

다음은 Stack 클래스의 주요 메서드이다.

리턴 타입 메서드 설명
E push(E item) 주어진 객체에 스택을 넣는다.
E pop() 스택의 맨 위 객체를 빼낸다.

 

다음은 동전 케이스를 Stack 클래스로 구현한 예제이다. 동전 케이스는 위에만 오픈되어 있는 스택 구조를 가진다. 먼저 넣은 동전은 맨 밑에 깔리고 나중에 넣은 동전이 위에 쌓이므로 제일 위의 동전부터 빼낼 수 있다.

package ch15;

public class Coin {
	private int value;
	
	public Coin(int value) {
		this.value = value;
	}
	
	public int getValue() { return value; }
	
}
package ch15;

import java.util.Stack;

public class StackExample {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		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() + "원");
		}
	}

}

 

출력 결과

꺼내온 동전: 10원
꺼내온 동전: 500원
꺼내온 동전: 50원
꺼내온 동전: 100원

 

Queue

Queue 인터페이스는 FIFO 자료구조에서 사용되는 메서드를 정의하고 있다. 다음은 Queue 인터페이스에 정의되어 있는 메서드이다.

리턴 타입 메서드 설명
boolean offer(E e) 주어진 객체를 큐에 넣는다.
E poll() 큐에서 객체를 빼낸다.

 

Queue 인터페이스를 구현한 대표적인 클래스는 LinkedList이다. 그렇기 때문에 LinkedList 객체를 Queue 인터페이스 변수에 다음과 같이 대입할 수 있다.

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

 

다음은 Queue를 이용해서 간단한 메시지 큐를 구현한 예제이다. 먼저 넣은 메시지가 반대쪽으로 먼저 나오기 때문에 넣은 순서대로 메시지가 처리된다.

package ch15;

public class Message {
	public String command;
	public String to;
	
	public Message(String command, String to) {
		this.command = command;
		this.to = to;
	}
}
package ch15;

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Queue<Message> messageQueue = new LinkedList<>();
		
		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;
			}
		}
	}

}

 

출력 결과

홍길동님에게 메일을 보냅니다.
신용권님에게 SMS를 보냅니다.
김자바님에게 카카오톡을 보냅니다.

 

'Language > JAVA' 카테고리의 다른 글

[JAVA] 수정할 수 없는 컬렉션  (1) 2024.10.18
[JAVA] 동기화된 컬렉션  (0) 2024.10.18
[JAVA] 검색 기능을 강화시킨 컬렉션  (0) 2024.10.18
[JAVA] Map 컬렉션  (0) 2024.10.18
[JAVA] Set 컬렉션  (0) 2024.10.18