Queue and Deque

table of Contents

Queue

(Message Queuing) Queue like queues of people standing in the front can buy go first, into the tail, the head of the queue.

Here Insert Picture Description

Common methods:

method Explanation
public boolean add(E e) Increased data, will throw an exception
public boolean offer(E e) Increase data return true if successful, will not throw an exception
public E remove() Delete data, will throw an exception
public E poll() Deleting data, do not throw an exception

LinkedList

LinkedList is a subclass of Queue.

Here Insert Picture Description

Example:

public class TestQueue {
    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();
        queue.add("1");
        queue.add("2");
        queue.add("4");
        queue.add("5");
        while(!queue.isEmpty()){
            System.out.print("【"+queue.poll()+"】、");
        }
    }
}

result:

1】、【2】、【4】、【5】、

PriorityQueue

PriorityQueue a priority queue will be output according to the natural order.

Here Insert Picture Description

Example:

public class TestPriorityQueue {
    public static void main(String[] args) {
        Queue<String> queue = new PriorityQueue<>();
        queue.add("a");
        queue.add("B");
        queue.add("A");
        queue.add("1");
        queue.add("9");
        queue.add("C");
        queue.add("x");
        queue.add("G");
        while(!queue.isEmpty()){
            System.out.print(queue.poll()+"、");
        }
    }
}

result:

19、A、B、C、G、a、x、	//根据ASCII码大小进行排序

and

Dqeue Queue is a subclass has the function of two-way queue, you can add data or pop-up data for the first or the tail.
Here Insert Picture Description

ArrayDeque

Here Insert Picture Description

Example:

public class TestDeque {
    public static void main(String[] args) {
        Deque<String> deque = new ArrayDeque<>();
        deque.offerFirst("hello");
        deque.offerLast("world");
        deque.offerFirst("2020");
        deque.offerLast("☆☆☆☆☆");
        //返回头部元素
        System.out.println(deque.peekFirst());
        //返回尾部元素
        System.out.println(deque.peekLast());
        while(!deque.isEmpty()){
            //弹出数据
            System.out.print(deque.poll()+"  ");
        }
    }
}

result:

2020
☆☆☆☆☆
2020  hello  world  ☆☆☆☆☆  
Published 61 original articles · won praise 0 · Views 2178

Guess you like

Origin blog.csdn.net/sabstarb/article/details/104651764