From e432360dc905aa13dee16affe12f80e197b4b5f0 Mon Sep 17 00:00:00 2001 From: Manuel Thalmann Date: Wed, 16 Nov 2022 22:52:07 +0100 Subject: [PATCH] Allow hashtable to be resized --- .../java/ch/nuth/zhaw/exbox/MyHashtable.java | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/ch/nuth/zhaw/exbox/MyHashtable.java b/app/src/main/java/ch/nuth/zhaw/exbox/MyHashtable.java index c0183b7..a6266d4 100644 --- a/app/src/main/java/ch/nuth/zhaw/exbox/MyHashtable.java +++ b/app/src/main/java/ch/nuth/zhaw/exbox/MyHashtable.java @@ -39,6 +39,21 @@ public class MyHashtable implements Map { 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 implements Map { 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); } }