From 88e17bfa4ff2be62385b57dca3d30a749a894a3e Mon Sep 17 00:00:00 2001 From: Taras Boychuk Date: Mon, 15 Jan 2024 10:24:34 +0200 Subject: [PATCH] GP-145 Fix resizeTable method to calculate HashTable size correctly --- .../main/java/com/bobocode/cs/HashTable.java | 5 +++-- .../java/com/bobocode/cs/HashTableTest.java | 22 +++++++++++++++---- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/2-0-data-structures-and-algorithms/2-2-9-hash-table/src/main/java/com/bobocode/cs/HashTable.java b/2-0-data-structures-and-algorithms/2-2-9-hash-table/src/main/java/com/bobocode/cs/HashTable.java index f7f8663f..1af07147 100644 --- a/2-0-data-structures-and-algorithms/2-2-9-hash-table/src/main/java/com/bobocode/cs/HashTable.java +++ b/2-0-data-structures-and-algorithms/2-2-9-hash-table/src/main/java/com/bobocode/cs/HashTable.java @@ -1,9 +1,9 @@ package com.bobocode.cs; -import static java.util.Objects.requireNonNull; - import lombok.ToString; +import static java.util.Objects.requireNonNull; + /** * {@link HashTable} is a simple Hashtable-based implementation of {@link Map} interface with some additional methods. * It is based on the array of {@link Node} objects. Both {@link HashTable} and {@link Node} have two type parameters: @@ -271,6 +271,7 @@ public String toString() { public void resizeTable(int newCapacity) { verifyCapacity(newCapacity); @SuppressWarnings("unchecked") Node[] newTable = new Node[newCapacity]; + size = 0; for (var head : table) { var current = head; while (current != null) { diff --git a/2-0-data-structures-and-algorithms/2-2-9-hash-table/src/test/java/com/bobocode/cs/HashTableTest.java b/2-0-data-structures-and-algorithms/2-2-9-hash-table/src/test/java/com/bobocode/cs/HashTableTest.java index b7355496..1a3565c2 100644 --- a/2-0-data-structures-and-algorithms/2-2-9-hash-table/src/test/java/com/bobocode/cs/HashTableTest.java +++ b/2-0-data-structures-and-algorithms/2-2-9-hash-table/src/test/java/com/bobocode/cs/HashTableTest.java @@ -503,10 +503,10 @@ class HashTableHelperMethodsTest { @Order(1) @DisplayName("resizeTable creates a new array and put there all elements") void resizeTable() { - addToTable("madmax", 833); - addToTable("altea", 553); - addToTable("AaAa", 123); - addToTable("BBBB", 456); + hashTable.put("madmax", 833); + hashTable.put("altea", 553); + hashTable.put("AaAa", 123); + hashTable.put("BBBB", 456); hashTable.resizeTable(16); @@ -518,6 +518,20 @@ void resizeTable() { } @Test + @Order(2) + @DisplayName("resizeTable does not change the size") + void resizeTableDoesNotChangeSize() { + hashTable.put("madmax", 833); + hashTable.put("altea", 553); + hashTable.put("AaAa", 123); + + hashTable.resizeTable(32); + + assertThat(hashTable.size()).isEqualTo(3); + } + + @Test + @Order(3) @DisplayName("toString returns a string that represents an underlying table") void toStringTest() { addToTable("madmax", 833);