Skip to content

Commit 3e5aafd

Browse files
committed
chore: add inline comments for improved clarity
resolves requested changes in PR
1 parent 4d53774 commit 3e5aafd

File tree

1 file changed

+14
-1
lines changed
  • src/main/java/dataStructures/hashSet/openAddressing

1 file changed

+14
-1
lines changed

src/main/java/dataStructures/hashSet/openAddressing/HashSet.java

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,13 @@ public boolean add(T element) {
6767
resize(capacity() * 2); // Resize to double the capacity.
6868
}
6969

70+
// Number of collisions encountered when attempting to insert the element into its rightful bucket
7071
int collisions = 0;
7172
while (collisions < capacity()) {
7273
int bucketIndex = hashFunction(element, collisions);
7374

74-
// Insert into empty bucket.
75+
// Insert into empty bucket. An empty bucket is defined as one that contains either a
76+
// Tombstone, or null.
7577
if (isEmptyBucket(bucketIndex)) {
7678
buckets[bucketIndex] = element;
7779
this.size++;
@@ -82,6 +84,10 @@ public boolean add(T element) {
8284
collisions++;
8385
}
8486

87+
// This line will only be reached if the number of empty buckets is zero.
88+
// With the resizing mechanism, the HashSet/buckets will expand to a larger capacity when a
89+
// certain threshold is reached. This means that there will always be empty buckets for adding of elements.
90+
assert false: "should never reach this line under normal circumstances, due to resizing mechanism";
8591
return false;
8692
}
8793

@@ -112,6 +118,8 @@ public boolean remove(T element) {
112118
int bucketIndex = hashFunction(element, collisions);
113119

114120
// Element is not removed, because it is not in the Set.
121+
// Unlike HashSet::add, HashSet::remove ignores buckets containing Tombstones.
122+
// Refer to README for a more detailed explanation.
115123
if (isNullBucket(bucketIndex)) {
116124
return false;
117125
}
@@ -146,13 +154,18 @@ public boolean contains(T element) {
146154
// added to bucket 3 instead of bucket 1, or bucket 2.
147155
// Similarly, to maintain that invariant, delete will not replace the element with null, but with a
148156
// marker (Tombstone).
157+
// If a bucket contains null in the probe sequence, we can be sure that the Set does not
158+
// contain the element, and return false immediately.
159+
// Unlike HashSet::add, HashSet::contains ignores buckets containing Tombstones.
160+
// Refer to README for a more detailed explanation.
149161
if (isNullBucket(bucketIndex)) {
150162
return false;
151163
}
152164

153165
if (buckets[bucketIndex].equals(element)) {
154166
return true;
155167
}
168+
156169
// Skips Tombstones/Deleted elements.
157170
collisions++;
158171
}

0 commit comments

Comments
 (0)