Skip to content

Commit 141aa9d

Browse files
committed
Add test for resize
1 parent 4c6d674 commit 141aa9d

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

test/dataStructures/hashSet/openAddressing/HashSetTest.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,4 +77,36 @@ public void testContains_afterRemove() {
7777

7878
assertTrue(hashSet.contains(25)); // contains should still find 25.
7979
}
80+
@Test
81+
public void testResize() {
82+
// Create a HashSet with an initial capacity of 16 and load factor of 0.75 for testing.
83+
HashSet<Integer> set = new HashSet<>();
84+
for (int i = 1; i <= 12; i++) {
85+
set.add(i);
86+
}
87+
88+
// Verify that the HashSet has the initial capacity of 16.
89+
assertEquals(16, set.capacity());
90+
91+
// Adding one more element should trigger a resize operation to double the capacity to 32.
92+
set.add(13);
93+
94+
// Verify that the HashSet has resized and doubled its capacity to 32.
95+
assertEquals(32, set.capacity());
96+
97+
// Removing elements until it triggers a resize operation to shrink the capacity.
98+
// Currently size is 13. Therefore, remove 5 elements.
99+
for (int i = 1; i <= 5; i++) {
100+
set.remove(i);
101+
}
102+
103+
// Verify that the HashSet has not resized.
104+
assertEquals(32, set.capacity());
105+
106+
// Removing one more element should trigger a resize operation to halve the capacity back to 16.
107+
set.remove(10);
108+
109+
// Verify that the HashSet has resized and halved its capacity back to 16.
110+
assertEquals(16, set.capacity());
111+
}
80112
}

0 commit comments

Comments
 (0)