Java-9.11 Queue
In this section, we will discuss the Queue.
The queue is very important for concurrency. Here we will just discuss it briefly and detail it later.
1. Features: first-in-first-out, which is different from the stack sequence.
2. Demo Method
Because the Queue List implements the Queue interface, we will use the Queue list as an example.
Package com. ray. ch09; import java. util. Utility list; import java. util. Queue; public class Test {public static void main (String [] args) {Queue
Queue = new queue list
(); For (int I = 0; I <10; I ++) {queue. add (I);} System. out. println (queue. toString (); for (int I = 0; I <queue. size (); I ++) {System. out. print (queue. peek (); // obtain the first element} System. out. println (); for (int I = 0; I <queue. size (); I ++) {System. out. print (queue. poll (); // remove and return the first element System. out. println (queue. toString ());}}}
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0000000000
0 [1, 2, 3, 4, 5, 6, 7, 8, 9]
1 [2, 3, 4, 5, 6, 7, 8, 9]
2 [3, 4, 5, 6, 7, 8, 9]
3 [4, 5, 6, 7, 8, 9]
4 [5, 6, 7, 8, 9]
For details about how to use this method, see the notes.
3. PriorityQueue
PriorityQueue is a queue with a default priority.
package com.ray.ch09;import java.util.PriorityQueue;import java.util.Random;public class Test {public static void main(String[] args) {PriorityQueue
integers = new PriorityQueue
();Random random = new Random();for (int i = 0; i < 10; i++) {integers.offer(random.nextInt(50));}System.out.println(integers.toString());PriorityQueue
strings = new PriorityQueue
();String text = d,e,T,g,qe,R,j,k,b,h,G,v,Kj,a,d,h,u,f,g,s,ad,jk,f,;String[] textArray = text.split(,);for (int i = 0; i < textArray.length; i++) {strings.offer(textArray[i]);}System.out.println(strings.toString());}}
Output:
[12, 14, 18, 18, 26, 41, 30, 44, 33, 43]
[G, R, Kj, e, ad, T, a, h, f, B, f, v, d, j, d, k, u, g, g, s, qe, jk, h]
Priority:
Numbers are from small to large
String is in upper case to lower case
Summary: This chapter describes some examples of queues.