Skip to content

Commit c3c16bb

Browse files
committed
Fix HashSet allowing duplicate elements
When elements are hashed to the same initial bucket, and then an element is removed, there is a possibility that a duplicate element can be inserted into the place of the deleted element.
1 parent 141aa9d commit c3c16bb

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

src/dataStructures/hashSet/openAddressing/HashSet.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,10 @@ public HashSet() {
6262
* element
6363
*/
6464
public boolean add(T element) {
65+
if (this.contains(element)) {
66+
return false;
67+
}
68+
6569
if (isLoadFactorExceeded()) {
6670
resize(this.capacity() * 2); // Resize to double the capacity.
6771
}
@@ -232,10 +236,6 @@ private int search(T element) {
232236
if (this.isNullBucket(currentBucketIndex)) {
233237
return ELEMENT_NOT_FOUND;
234238
}
235-
// if bucket contains TOMBSTONE, skip checking current bucket index for equality.
236-
if (this.isTombstoneBucket(currentBucketIndex)) {
237-
continue;
238-
}
239239

240240
// Checks equality of elements using Object::equals and Object::hashCode.
241241
if (this.buckets[currentBucketIndex].equals(element)

0 commit comments

Comments
 (0)