2010-08-15 34 views
0

我有一個索引,每當有新數據進入Web應用程序時,我都需要重新排序。在產品ID的內存索引中,按inventory_count排序

我在內存中列出了每種產品的產品清單和inventoryCount。

我想保留一個productID的索引,按庫存數量排序。

因此,如果新訂單進來,庫存會被修改,所以我必須更新product_inventory索引。

這樣做的最快方法是什麼?

我不能使用這個數據庫,它必須是內存中的所有通過java代碼

+0

內存數據庫如HSQLDB如何? http://hsqldb.org/ – karim79 2010-08-15 23:28:51

+0

沒有數據庫,只是通過代碼。 – Blankman 2010-08-15 23:36:13

+0

這似乎是一個相當武斷的要求。你介意爲什麼會出現這種情況嗎? – 2010-08-15 23:59:56

回答

1

您可以使用一個比較器來維持維持庫存數的順序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一樣,以避免裝箱/取消裝箱整數值的開銷。