從頭認識java-9.11 Queue

來源:互聯網
上載者:User

從頭認識java-9.11 Queue

這一章節我們來討論一下隊列Queue。

隊列對於並發非常的重要,我們這裡只是簡單討論一下,在以後講述並發的時候將詳細展開。

1.特性:先進先出,它跟棧的順序不一樣。

 

2.示範方法

由於LinkedList實現了Queue介面,因此我們將以LinkedList作為例子。

 

package com.ray.ch09;import java.util.LinkedList;import java.util.Queue;public class Test {public static void main(String[] args) {Queue queue = new LinkedList();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());// 拿出第一個元素}System.out.println();for (int i = 0; i < queue.size(); i++) {System.out.print(queue.poll());// 去掉並返回第一個元素System.out.println(queue.toString());}}}

輸出:

 

[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]

 

具體方法的使用,可以看注釋。

 

3.PriorityQueue

PriorityQueue是一個有預設優先順序的隊列

 

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());}}
輸出:

 

[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]

優先順序:

數字是從小到大

字串是大寫到小寫

 

總結:這一章節主要講述了隊列的一些例子。

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.