您可以使用一個比較器來維持維持庫存數的順序productIDs的列表。比較器根據產品ID查找庫存盤點並將其作爲比較的基礎。
假設你有類:
class Product {
int productID;
int inventoryCount;
}
比較會是什麼樣子:
class ProductInventoryComparator implements Comparator<Product> {
public int compare(Product p1, Product p2) {
return p1.inventoryCount-p2.inventoryCount;
}
}
有了這個,你就可以通過在正確的位置插入元素,以保持維持一個有序列表該列表已排序。要在列表中找到插入的地方,使用Collections.binarySearch定位插入點:
ProductInventoryComparator comp = new ProductInventoryComparator();
List<Product> productList = new ArrayList<Product>();
Product p = ...new product to add;
int pos = Collections.binarySearch(productList, comp, p);
if (pos<0) { // not found
productList.add(-pos-1);
}
你提到你想ProductIDs,想必整數列表的列表 - 如果可能的話我建議您爲這些簡單對象像上面的Product一樣,以避免裝箱/取消裝箱整數值的開銷。
內存數據庫如HSQLDB如何? http://hsqldb.org/ – karim79 2010-08-15 23:28:51
沒有數據庫,只是通過代碼。 – Blankman 2010-08-15 23:36:13
這似乎是一個相當武斷的要求。你介意爲什麼會出現這種情況嗎? – 2010-08-15 23:59:56