Skip to content

Commit 160f1e4

Browse files
committed
Add HashSet data structure implementation for integers (#6304)
1 parent 054002a commit 160f1e4

1 file changed

Lines changed: 63 additions & 0 deletions

File tree

  • src/main/java/com/thealgorithms/datastructures/hashset
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
2+
package com.thealgorithms.datastructures.hashset;
3+
4+
/**
5+
* Example usage:
6+
* <pre>
7+
* HashSet set = new HashSet();
8+
* set.add(5);
9+
* set.add(10);
10+
* System.out.println(set.contains(5)); // true
11+
* set.remove(5);
12+
* System.out.println(set.contains(5)); // false
13+
* </pre>
14+
*/
15+
16+
import java.util.LinkedList;
17+
18+
/**
19+
* A simple implementation of a HashSet for integers using separate chaining.
20+
*/
21+
public class HashSet {
22+
private static final int INITIAL_CAPACITY = 16;
23+
private LinkedList<Integer>[] buckets;
24+
private int size;
25+
26+
@SuppressWarnings("unchecked")
27+
public HashSet() {
28+
buckets = new LinkedList[INITIAL_CAPACITY];
29+
for (int i = 0; i < INITIAL_CAPACITY; i++) {
30+
buckets[i] = new LinkedList<>();
31+
}
32+
size = 0;
33+
}
34+
35+
private int hash(int key) {
36+
return Math.abs(key) % buckets.length;
37+
}
38+
39+
public void add(int key) {
40+
int idx = hash(key);
41+
if (!buckets[idx].contains(key)) {
42+
buckets[idx].add(key);
43+
size++;
44+
}
45+
}
46+
47+
public boolean contains(int key) {
48+
int idx = hash(key);
49+
return buckets[idx].contains(key);
50+
}
51+
52+
public void remove(int key) {
53+
int idx = hash(key);
54+
if (buckets[idx].remove((Integer) key)) {
55+
size--;
56+
}
57+
}
58+
59+
public int size() {
60+
return size;
61+
}
62+
}
63+

0 commit comments

Comments
 (0)