日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java的优先队列注意事项

發布時間:2023/12/31 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java的优先队列注意事项 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在C++語言中,使用優先隊列,直接構建一個lambda表達式,使用一個匿名函數指針。java比較函數的返回值不是bool型,只能是整型。

內部對應的C++匿名函數:

// 匿名Comparator實現

auto compareMax = []( const Cell &a, const Cell &b ) { return a.max < b.max; };

對應的Java函數:

import java.util.Queue; import java.util.Comparator; import java.util.PriorityQueue;// 匿名Comparator實現public static Comparator<Cell> compareMax = new Comparator<Cell>() {@Overridepublic int compare(Cell c1, Cell c2) {if (c1.max < c2.max)return 1;elsereturn -1;}};

匿名比較函數實現,java使用int型,返回值為1-1C++可以使用boolean型。其實應該寫一個lambda表達式的

?

Java優先隊列的使用:

Queue<Cell> cellQueue = new PriorityQueue( compareMax );
對應C++ 優先隊列的使用:

using Queue = std::priority_queue< Cell<T>, std::vector<Cell<T> >, decltype(compareMax)>; Queue<Cell> cellQueue = new PriorityQueue(compareMax);


實現功能,在插入時,可以使用c.max進行排序插入。

?

參考:java函數式編程之lambda表達式

匿名類實現匿名函數:

public void testAnonymousClass() {Integer[] nums = {2, 5, 1, 6};Arrays.sort(nums, new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {if(o1 < o2)return -1;return 0;}});for (Integer n : nums) {System.out.println(n);} }
lambda 表達式:

public void testAnonymousClass() {Integer[] nums = {2, 5, 1, 6};Arrays.sort(nums, (o1, o2) -> {if(o1 < o2)return -1;return 0;});for (Integer n : nums) {System.out.println(n);} }

?參考:javaqueue的使用

??? Queue接口與List、Set同一級別,都是繼承了Collection接口。LinkedList實現了Queue接 口。Queue接口窄化了對LinkedList的方法的訪問權限(即在方法中的參數類型如果是Queue時,就完全只能訪問Queue接口所定義的方法 了,而不能直接訪問 LinkedList的非Queue的方法),以使得只有恰當的方法才可以使用。BlockingQueue 繼承了Queue接口。

add??????? 增加一個元索???????????????????? 如果隊列已滿,則拋出一個IIIegaISlabEepeplian異常
remove?? 移除并返回隊列頭部的元素??? 如果隊列為空,則拋出一個NoSuchElementException異常
element??返回隊列頭部的元素???????????? 如果隊列為空,則拋出一個NoSuchElementException異常
offer?????? 添加一個元素并返回true???????如果隊列已滿,則返回false
poll???????? 移除并返問隊列頭部的元素????如果隊列為空,則返回null
peek?????? 返回隊列頭部的元素???????????? 如果隊列為空,則返回null
put???????? 添加一個元素????????????????????? 如果隊列滿,則阻塞
take??????? 移除并返回隊列頭部的元素???? 如果隊列為空,則阻塞

removeelementoffer?pollpeek?其實是屬于Queue接口。?

?

參考:java8 手把手教你學會寫lambda表達式



總結

以上是生活随笔為你收集整理的java的优先队列注意事项的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。