개발/Java collection framework

[Java] LIFO와 FIFO 컬랙션

두리두리안 2021. 6. 15. 16:39

후입선출(LIFO)은 나중에 넣은 객체가 먼저 빠져나가는 자료구조를 말한다. 

선입선출(FIFO)은 먼저 넣은 객체가 먼저 빠져나가는 구조를 말한다. 

 

컬렉션 프레임워크에는 LIFO 자료구조를 제공하는 스택(Stack)클래스와 FIFO 자료구조를 제공하는 큐 인터페이스를 제공


Stack

Stack 클래스는 LIFO 자료구조를 구현한 클래스 이다. 밑에는 Stack 클래스의 주요 메소드들이다.

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

 

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

 

package Part15_프레임워크.Stack;

public class Coin {
    private int value;

    public Coin(int value){
        this.value = value;
    }
    public int getValue(){
        return value;
    }
}

 

package Part15_프레임워크.Stack;

import java.util.Stack;

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

        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 인터페이스는 FIFO 자료구조에서 사용되는 메소드를 정의하고 있다.

 

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

 

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

 

package Part15_프레임워크.Queue;

public class Message {
    public String command;
    public String to;

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

 

package Part15_프레임워크.Queue;

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

public class QueueExample {
    public static void main(String[] args){
        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;
            }
        }
    }
}