Allow hashtable to be resized
This commit is contained in:
parent
f907dc03af
commit
e432360dc9
|
@ -39,6 +39,21 @@ public class MyHashtable<K, V> implements Map<K, V> {
|
|||
return -1;
|
||||
}
|
||||
|
||||
private void resize(int size) {
|
||||
int oldSize = this.size;
|
||||
int oldCapacity = capacity;
|
||||
K[] oldKeys = keys;
|
||||
V[] oldValues = values;
|
||||
capacity = size;
|
||||
clear();
|
||||
this.size = oldSize;
|
||||
|
||||
for (int i = 0; i < oldCapacity; i++) {
|
||||
keys[i] = oldKeys[i];
|
||||
values[i] = oldValues[i];
|
||||
}
|
||||
}
|
||||
|
||||
// Removes all mappings from this map (optional operation).
|
||||
public void clear() {
|
||||
size = 0;
|
||||
|
@ -53,11 +68,16 @@ public class MyHashtable<K, V> implements Map<K, V> {
|
|||
|
||||
if (index == -1) {
|
||||
size++;
|
||||
|
||||
if (size > capacity) {
|
||||
resize(capacity * 2);
|
||||
}
|
||||
|
||||
int hashCode = hash(key);
|
||||
index = hashCode;
|
||||
|
||||
for (int i = 0; keys[index] != null && !keyEquals(keys[index], key); i++) {
|
||||
index = hash(hashCode + (int) Math.pow(i, 2));
|
||||
for (int i = 0; keys[index] != null; i++) {
|
||||
index = hash(hashCode + i);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue