Skip to content

Commit 197403b

Browse files
committed
Implement resize method body
1 parent 413d4ff commit 197403b

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/dataStructures/hashSet/openAddressing/HashSet.java

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.util.Arrays;
44
import java.util.List;
5+
import java.util.Objects;
56
import java.util.stream.Collectors;
67

78
/**
@@ -263,8 +264,21 @@ private int capacity() {
263264
* or if the load factor falls below 1/4 (arbitrary) of the capacity (and the capacity is larger than the minimum capacity), the
264265
* capacity is decreased by halving it (possibly triggered after a remove operation).
265266
*/
266-
private void resize() {
267-
throw new UnsupportedOperationException("Table is full");
267+
private void resize(int newCapacity) {
268+
// creates a temporary reference to the original bucket
269+
T[] temp = this.buckets;
270+
271+
// Safe cast because the only way to add elements into this HashSet is through the add method, which
272+
// only takes in elements of type T.
273+
@SuppressWarnings("unchecked")
274+
T[] newBuckets = (T[]) new Object[newCapacity];
275+
this.buckets = newBuckets;
276+
277+
// re-hashes every element and re-insert into the newly created buckets.
278+
Arrays.stream(temp)
279+
.filter(Objects::nonNull)
280+
.filter(element -> !element.equals(this.TOMBSTONE))
281+
.forEach(this::add);
268282
}
269283

270284
/**

0 commit comments

Comments
 (0)