[英]Collections Sort and Binarysearch and lambda comparator
我有一個對象 Customer,其屬性 id 是一個 int。 我正在嘗試使用帶有 lambda 比較器的 Collections 內置排序和搜索功能。 我的問題是,為什么這似乎有效:
Collections.sort(customers, (a, b) -> a.getID() - b.getID());
但這不會:
foundIndex = Collections.binarySearch(customers, custID,
(a, b) -> a.getID() - b.getID());
當我說“似乎有效”時,我的意思是它運行時沒有錯誤。 特別是第二行,Eclipse 有.getID()
問題。 它給了我一個鑄造建議,我嘗試過:
foundIndex = Collections.binarySearch(customers, custID,
(a, b) -> ((Customer) a).getID() - ((Customer) b).getID());
但這遇到了一個運行時錯誤,說“Integer can not be cast to class Customer”當我嘗試在(a, b)
Eclipse 也不喜歡那樣。 任何 lambda 都會在 binarySearch 部分做我想要的嗎?
您是否嘗試過提供 Customer 類的實例而不是 ID?
foundIndex = Collections.binarySearch(customers, customer,
(a, b) -> a.getID() - b.getID());
正如評論者 Silvio Mayolo 所說,問題實際上並不是 lambda,而是Collections.binarySearch()
的關鍵參數所期望的。
這完全符合我的要求:
//assumes presorted customers ArrayList, thank you commenter gOOse
public Customer findCustomer(int custID) {
int foundIndex;
Customer key = new Customer(custID, null);
readLock.lock();
try {
foundIndex = Collections.binarySearch(customers, key,
(a, b) -> a.getID() - b.getID());
return (foundIndex > -1) ? customers.get(foundIndex) : null;
}
finally { readLock.unlock(); }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.