Repository: TheAlgorithms/Java
Pull request #5974 (2024-10-24 06:02:59)

refactor: Add more tests in `HashMap`
<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5974?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `85.71429%` with `1 line` in your changes missing coverage. Please review.
> Project coverage is 67.98%. Comparing base [(`5246f63`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/5246f635797194f5f0d7ac93af61099a5764fa4f?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`9c3f2fa`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/9c3f2fa40ae811a4b74593c85eab26b2cdc25d54?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5974?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...rithms/datastructures/hashmap/hashing/HashMap.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5974?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fdatastructures%2Fhashmap%2Fhashing%2FHashMap.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9kYXRhc3RydWN0dXJlcy9oYXNobWFwL2hhc2hpbmcvSGFzaE1hcC5qYXZh) | 85.71% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5974?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@            Coverage Diff            @@
##             master    #5974   +/-   ##
=========================================
  Coverage     67.98%   67.98%           
- Complexity     4586     4590    +4     
=========================================
  Files           620      620           
  Lines         17116    17123    +7     
  Branches       3305     3307    +2     
=========================================
+ Hits          11636    11641    +5     
  Misses         5035     5035           
- Partials        445      447    +2     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5974?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java
index 1aae122b..aed39c94 100644
--- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java
+++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java
@@ -85,6 +85,28 @@ public class HashMap<K, V> {
         }
     }
 
+    /**
+     * Clears the contents of the hash map by reinitializing each bucket.
+     */
+    public void clear() {
+        for (int i = 0; i < hashSize; i++) {
+            buckets[i] = new LinkedList<>();
+        }
+    }
+
+    /**
+     * Gets the number of key-value pairs in the hash map.
+     *
+     * @return the number of key-value pairs in the hash map
+     */
+    public int size() {
+        int size = 0;
+        for (int i = 0; i < hashSize; i++) {
+            size += buckets[i].isEmpty() ? 0 : 1;
+        }
+        return size;
+    }
+
     /**
      * A nested static class that represents a linked list used for separate chaining in the hash map.
      *


Test patch:
diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapTest.java
index 3552bc1a..ff3ba3ed 100644
--- a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapTest.java
+++ b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapTest.java
@@ -17,7 +17,7 @@ public class HashMapTest {
         assertEquals("Value15", hashMap.search(15));
         assertEquals("Value25", hashMap.search(25));
         assertEquals("Value35", hashMap.search(35));
-        assertNull(hashMap.search(45));
+        assertNull(hashMap.search(45)); // Test for non-existent key
     }
 
     @Test
@@ -29,7 +29,7 @@ public class HashMapTest {
 
         assertEquals("Value25", hashMap.search(25));
         hashMap.delete(25);
-        assertNull(hashMap.search(25));
+        assertNull(hashMap.search(25)); // Confirm deletion
     }
 
     @Test
@@ -38,21 +38,22 @@ public class HashMapTest {
         hashMap.insert(15, "Value15");
         hashMap.insert(25, "Value25");
         hashMap.insert(35, "Value35");
-        hashMap.display();
+        // Optionally verify display functionality if it returns a string
+        hashMap.display(); // Manual check during test execution
     }
 
     @Test
     public void testInsertNullKey() {
         HashMap<Integer, String> hashMap = new HashMap<>(10);
         hashMap.insert(null, "NullValue");
-        assertEquals("NullValue", hashMap.search(null));
+        assertEquals("NullValue", hashMap.search(null)); // Verify null key handling
     }
 
     @Test
     public void testInsertNullValue() {
         HashMap<Integer, String> hashMap = new HashMap<>(10);
         hashMap.insert(15, null);
-        assertNull(hashMap.search(15));
+        assertNull(hashMap.search(15)); // Verify null value handling
     }
 
     @Test
@@ -61,12 +62,12 @@ public class HashMapTest {
         hashMap.insert(15, "Value15");
         hashMap.insert(15, "UpdatedValue15");
 
-        assertEquals("UpdatedValue15", hashMap.search(15));
+        assertEquals("UpdatedValue15", hashMap.search(15)); // Verify update
     }
 
     @Test
     public void testHandleCollisions() {
-        HashMap<Integer, String> hashMap = new HashMap<>(3);
+        HashMap<Integer, String> hashMap = new HashMap<>(3); // Create a small bucket size to force collisions
         // These keys should collide if the hash function is modulo 3
         hashMap.insert(1, "Value1");
         hashMap.insert(4, "Value4");
@@ -80,17 +81,17 @@ public class HashMapTest {
     @Test
     public void testSearchInEmptyHashMap() {
         HashMap<Integer, String> hashMap = new HashMap<>(10);
-        assertNull(hashMap.search(10));
+        assertNull(hashMap.search(10)); // Confirm search returns null in empty map
     }
 
     @Test
     public void testDeleteNonExistentKey() {
         HashMap<Integer, String> hashMap = new HashMap<>(10);
         hashMap.insert(15, "Value15");
-        hashMap.delete(25);
+        hashMap.delete(25); // Delete non-existent key
 
-        assertEquals("Value15", hashMap.search(15));
-        assertNull(hashMap.search(25));
+        assertEquals("Value15", hashMap.search(15)); // Ensure existing key remains
+        assertNull(hashMap.search(25)); // Confirm non-existent key remains null
     }
 
     @Test
@@ -101,7 +102,7 @@ public class HashMapTest {
         }
 
         for (int i = 0; i < 100; i++) {
-            assertEquals("Value" + i, hashMap.search(i));
+            assertEquals("Value" + i, hashMap.search(i)); // Verify all inserted values
         }
     }
 
@@ -113,7 +114,7 @@ public class HashMapTest {
         hashMap.insert(7, "Value7");
 
         hashMap.delete(1);
-        assertNull(hashMap.search(1));
+        assertNull(hashMap.search(1)); // Verify head deletion
         assertEquals("Value4", hashMap.search(4));
         assertEquals("Value7", hashMap.search(7));
     }
@@ -126,7 +127,7 @@ public class HashMapTest {
         hashMap.insert(7, "Value7");
 
         hashMap.delete(7);
-        assertNull(hashMap.search(7));
+        assertNull(hashMap.search(7)); // Verify tail deletion
         assertEquals("Value1", hashMap.search(1));
         assertEquals("Value4", hashMap.search(4));
     }
@@ -139,8 +140,45 @@ public class HashMapTest {
         hashMap.insert(7, "Value7");
 
         hashMap.delete(4);
-        assertNull(hashMap.search(4));
+        assertNull(hashMap.search(4)); // Verify middle element deletion
         assertEquals("Value1", hashMap.search(1));
         assertEquals("Value7", hashMap.search(7));
     }
+
+    @Test
+    public void testResizeHashMap() {
+        HashMap<Integer, String> hashMap = new HashMap<>(2); // Small initial size to force rehashing
+        for (int i = 0; i < 10; i++) {
+            hashMap.insert(i, "Value" + i);
+        }
+
+        // Verify all values after resizing
+        for (int i = 0; i < 10; i++) {
+            assertEquals("Value" + i, hashMap.search(i));
+        }
+    }
+
+    @Test
+    public void testCollisionResolution() {
+        HashMap<String, String> hashMap = new HashMap<>(3);
+        hashMap.insert("abc", "Value1"); // Hash index 0
+        hashMap.insert("cab", "Value2"); // Hash index 0 (collision)
+        hashMap.insert("bac", "Value3"); // Hash index 0 (collision)
+
+        assertEquals("Value1", hashMap.search("abc"));
+        assertEquals("Value2", hashMap.search("cab"));
+        assertEquals("Value3", hashMap.search("bac"));
+    }
+
+    @Test
+    public void testClearHashMap() {
+        HashMap<Integer, String> hashMap = new HashMap<>(10);
+        hashMap.insert(1, "Value1");
+        hashMap.insert(2, "Value2");
+
+        hashMap.clear(); // Assuming clear method resets the hash map
+        assertNull(hashMap.search(1));
+        assertNull(hashMap.search(2));
+        assertEquals(0, hashMap.size()); // Verify size is reset
+    }
 }