One of my assignment is to implement my own version of the hash table. I have nearly completed the
assignment except one test keeps failing. Any advice would be much appreciated.
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;
}
}
You should review your resize() method.
// 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];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.