Java哈希表

时间:2015-01-06 10:45:15

标签: java

我的任务之一是实现我自己的哈希表版本。我差不多完成了    分配除了一个测试一直失败。任何建议都将不胜感激。

import java.math.BigInteger;
import java.util.Collection;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;

/**
 * Resize the hashtable, to be used when the load factor exceeds maxLoad. The new size of
 * the underlying array should be the smallest prime number which is at least twice the size
 * of the old array.
 */
private void resize() {
    if(getLoadFactor() >= maxLoad){
        itemCount = 0;
        int newCapacity = nextPrime(max * 2+1);
        int i = 0;

        Collection<String> c = getKeys();
        arr = new Pair[newCapacity];

        for (String key : c)
        {   int hashKey = hash(key) % newCapacity;
             V v = get(key);
            if(arr[hashKey] == null){
                arr[hashKey] = new Pair<V>(key,v);
                  itemCount++;
            }else{
                int position =  findEmpty(i, i, key);
                arr[position] = new Pair<V>(key,v);
                  itemCount++;
            }
        }



        max = newCapacity;
    }
}

1 个答案:

答案 0 :(得分:0)

你应该检查你的resize()方法。

// you keep all keys
Collection<String> c = getKeys(); 
// you create a new array of Pairs for the new capacity but you lose at the same time all previous values
arr = new Pair[newCapacity];