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和-1,C++可以使用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);} }
?參考:java中queue的使用
??? 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??????? 移除并返回隊列頭部的元素???? 如果隊列為空,則阻塞
remove、element、offer?、poll、peek?其實是屬于Queue接口。?
?
參考:java8 手把手教你學會寫lambda表達式
總結
以上是生活随笔為你收集整理的java的优先队列注意事项的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VS编译时使用/去除NuGet管理库
- 下一篇: 头上三尺有神明不畏人知畏己知的意思是