java的優先隊列注意事項__人形機器人

來源:互聯網
上載者:User

在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>() {        @Override        public int compare(Cell c1, Cell c2) {            if (c1.max < c2.max)                return 1;            else                return -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>() {        @Override        public 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運算式



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.