[英]Java hash table
我的任务之一是实现我自己的哈希表版本。 我几乎完成了
分配,但一项测试始终失败。 任何建议将不胜感激。
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;
}
}
您应该查看您的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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.