Java-15.6 Queue (Queue)
In this section, we will discuss the Queue ).
1. What is a queue?
A queue is a special linear table. It allows only the front-end of the table to be deleted, and the insert operation on the back-end (rear) of the table, like a stack, a queue is a linear table with limited operations.
2. Features
(1) elements are ordered.
(2) elements are first-in-first-out
3. Implementation classes in java: shortlist and PriorityQueue. There is no difference in performance between the two. The difference lies in sorting.
package com.ray.ch14;import java.util.LinkedList;import java.util.PriorityQueue;import java.util.Queue;public class Test {public static
void test(Queue
queue, Generator
generator,int count) {for (int i = 0; i < count; i++) {queue.add(generator.next());}while (queue.peek() != null) {System.out.print(queue.remove() + " ");}System.out.println();}public static void main(String[] args) {test(new LinkedList
(), new MyGenerator(), 10);test(new PriorityQueue
(), new MyGenerator(), 10);}}interface Generator
{T next();}class MyGenerator implements Generator
{private String str = "one two three four five six seven eight nine ten eleven";private int index = 0;@Overridepublic String next() {if (index > str.split(" ").length) {return "";} else {return str.split(" ")[index++];}}}
Output:
One two three four five six seven eight nine ten
Eight five four nine one seven six ten three two
4. priority queue
You can implement the Comparable interface for sorting objects.
package com.ray.ch14;import java.util.PriorityQueue;import java.util.Random;public class Test {private static PriorityQueue
priorityQueue = new PriorityQueue
();public static PriorityQueue
test(int count) {for (int i = 0; i < count; i++) {priorityQueue.add(new MyClass(new Random().nextInt(10)));}return priorityQueue;}public static void main(String[] args) {System.out.println(test(10));}}class MyClass implements Comparable
{private int pri = 0;public MyClass(int pri) {this.pri = pri;}@Overridepublic int compareTo(MyClass myClass) {if (this.pri < myClass.pri) {return -1;} else {if (this.pri == myClass.pri) {return 0;} else {return 1;}}}@Overridepublic String toString() {return this.pri + "";}}
Output:
[0, 1, 3, 3, 2, 5, 5, 6, 6, 7]
5. Bidirectional queue
Feature: You can add or delete elements in any segment.
As there is no interface to implement bidirectional queue in the existing java, but it has been simulated in the queue list, so we use a combination to simulate it.
class Deque
{private LinkedList
linkedList = new LinkedList
();public void addFirst(T t) {linkedList.addFirst(t);}public void addLast(T t) {linkedList.addLast(t);}public void removeFirst() {linkedList.removeFirst();}public void removeLast() {linkedList.removeLast();}}
Summary: This chapter describes the concept and features of queues, as well as priority and bidirectional queues.
This chapter is here. Thank you.