Programming/Java

[Java] - Deque 기본 사용법

구튼탁 2021. 3. 6. 13:57
728x90

https://www.geeksforgeeks.org/deque-interface-java-example/

Deque(double ended queue)

public interface Deque<E> extends Queue<E>
A linear collection that supports element insertion and removal at both ends.

The name deque is short for "double ended queue" and is usually pronounced "deck". Most Deque implementations place no fixed limits on the number of elements they may contain, but this interface supports capacity-restricted deques as well as those with no fixed size limit.

All Known Implementing Classes:ArrayDeque, ConcurrentLinkedDeque, LinkedBlockingDeque, LinkedList

 

 

deque는 데이터를 선형 자료구조 시작과 끝에 추가, 삭제할 수 있다. 즉, 스택과 큐를 합쳐놓은 것과 같으며

스택으로 사용할 수도 있고, 큐로 사용할 수도 있다. 

ArrayDeque, ConcurrentLinkedDeque, LinkedBlockingDeque, LinkedList 중에 하나를 구현체로 선택하면 된다.

기본 코드

package com.java.collectionFrameowork;

import java.util.Deque;
import java.util.LinkedList;

public class DequeueEx01 {

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

        // Add at the last
        deque.add("Element 1 (Tail)");
        // Add at the first
        deque.addFirst("Element 2 (Head)");
        // Add at the last
        deque.addLast("Element 3 (Tail)");
        // Add at the first
        deque.push("Element 4 (Head)");
        // Add at the last
        deque.offer("Element 5 (Tail)");
        // Add at the first
        deque.offerFirst("Element 6 (Head)");

        System.out.println(deque + "\n");

        // We can remove the first element
        // or the last element.
        deque.removeFirst();
        deque.removeLast();
        System.out.println("Deque after removing "
                + "first and last: "
                + deque);
    }
}

 

[Element 6 (Head), Element 4 (Head), Element 2 (Head), Element 1 (Tail), Element 3 (Tail), Element 5 (Tail)]

Deque after removing first and last: [Element 4 (Head), Element 2 (Head), Element 1 (Tail), Element 3 (Tail)]

 

728x90