programming/JAVA

[Java] Queue 사용하기(add vs offer)

LeeBorn 2021. 7. 21. 21:24
반응형

프로그래밍

Queue 사용법

Java에서 정의되어 있는 Queue를 사용해보자.

무심코 아래와 같이 작성하면 생각한 대로 작동하지 않는다.

Queue<String> queue = new Queue<String>();

 

IDE를 사용해서 작성해보면 아래와 같이 자동 완성된 코드를 볼 수 있다.

new Queue() ???

Queue는 인터페이스로만 제공되어서 따로 구현체를 사용해야 한다.

인텔리제이를 사용할 때는 LinkdeList <>를 추천해준다.

나머진 목적에 맞게 사용하면 된다.

Queue와 LinkedList

 

add()

먼저 add()를 사용해서 큐에 하나씩 추가할 수 있다.

    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();

        queue.add("일");
        queue.add("이");
        queue.add("삼");
        queue.add("사");
        queue.add("오");

        queue.forEach(System.out::print);
    }

 

 

실행결과

 

poll(), peek()

실행한 것들을 꺼낼 때는 poll()을 사용해 꺼낼 수 있다.

        System.out.println("poll() 1 : " + queue.poll());
        System.out.println("poll() 2 : " + queue.poll());
        System.out.println("=====================");
        System.out.println("peek() 1 : " + queue.peek());
        System.out.println("peek() 2 : " + queue.peek());

 

이때 실행결과는 아래와 같다.

실행 결과

poll()은 먼저 넣은 것들(head)부터 하나씩 반환하고, 그것을 삭제한다.

(그래서 "일", "이"가 순서대로 출력된다.)

 

peek()는 먼저 넣은 것들(head)를 하나씩 반환하지만, 삭제하지 않는다.

(peek()를 2번 실행했지만, "삼"을 2번 반환한다.)

 

기타

1. 이 글을 작성한 이유는 코딩 테스트 중 Queue를 사용하기를 바라는 것 같은 문제가 있었는데,

생각이 나지 않아서 ArrayList()를 사용해 풀었는데, 그 정리 겸 작성한다.

2. 추가할 때 offer()를 사용할 수 도 있다.

add()와 offer()는 아래와 같다.

public class LinkedList<E>
       extends AbstractSequentialList<E>
            implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    /**
     * Adds the specified element as the tail (last element) of this list.
     * ~ ~ ~
     */
    public boolean offer(E e) { return add(e); }

    /**
     * Appends the specified element to the end of this list. This method is equivalent to addLast.
     * ~ ~ ~
     */
    public boolean add(E e) {
        linkLast(e);
        return true;
    }
}

 


 

- 작성된 글에는 잘못된 부분이 있을 수 있습니다. 알려주시면 반영하겠습니다.

※ info
IDE : IntelliJ IDEA 2021.1.3 (Ultimate Edition)
Java : openjdk version "11.0.2"
OS : macOS Big Sur "11.4"
반응형