2012-11-16 47 views
0

我無法弄清楚如何加倍散列表的大小。下面是代碼:卡在散列表的大小加倍

private void doubleLength() { 
    //Remember the old hash table array and allocate a new one 2 times as big 

    HashMap<K,V> resizedMap = new HashMap<K,V>(map.length * 2); 

/*Traverse the old hash table adding each value to the new hash table. 
Instead, add it to by applying 
hashing/compression again (compression will be DIFFERENT, because the 
length of the table is doubled, so we compute the same hash value but 
compute the remainder using the DIFFERENT TABLE LENGTH).*/ 
    for (int i = 0; i < map.length; i++) { 
     for (K key : map[i].entry) { //iterator does not work here 
        resizedMap.put(key, map[i].get(key)); //should go here 
    } 

} 

哈希表LN對象的數組,其中LN被定義爲:

public static class LN<K1,V1> { 
    public Map.Entry<K1,V1> entry; 
    public LN<K1,V1>  next; 

    public LN (Map.Entry<K1,V1> e, LN<K1,V1> n) 
    {entry = e; next = n;} 
} 

我有類中可迭代但它不允許在地圖[ I] .entry.entries()。

public Iterable<Map.Entry<K,V>> entries() { 
return new Iterable<Map.Entry<K,V>>() { 
    public Iterator<Map.Entry<K,V>> iterator() { 
    return new MapEntryIterator(); 
    } 
}; 
} 

我很迷茫,我怎麼能把公共LN的大小加倍[] map;

+0

我很困惑。後面的兩個代碼片斷表明你正在實現自己的散列表,但第一個代碼片斷表明你正在使用java.util.HashMap。 –

回答

3

當散列表變得太滿時,HashMap已經調整了自己的大小。你不必調整它。

0

您的代碼不會編譯。如果你想初始化地圖規模翻番很容易做到這一點(假設mapMap也):

private void doubleLength() { 
    //Remember the old hash table array and allocate a new one 2 times as big 
    HashMap<K,V> resizedMap = new HashMap<K,V>(map.size()* 2); 
    resizedMap.putAll(map); 
} 

而且你似乎很奇怪的東西訪問。如果你通過地圖需要循環播放shoudl樣子:

for (K key : map.keySet()){ 
    V value = map.get(key); //get the value from the map 
    //do what you need to do 
} 

現在如前所述,您不需要調整HashMap中。它已經這樣做了。從JavaDocs

一個HashMap的實例有兩個影響其性能參數: 初始容量和負載因子。容量是散列表中的 存儲桶的數量,初始容量僅僅是在創建散列表時的容量爲 。加載因子是 衡量散列表在其容量自動增加之前被允許獲得的滿度的度量。當散列表中的條目數超過了負載因子和當前容量的乘積時,散列表就會被重新映射(即內部數據 結構被重建),因此散列表約有兩次 這個數的水桶。