diff --git a/src/main/java/com/thealgorithms/datastructures/hashset/HashSet.java b/src/main/java/com/thealgorithms/datastructures/hashset/HashSet.java new file mode 100644 index 000000000000..7e97c7e56678 --- /dev/null +++ b/src/main/java/com/thealgorithms/datastructures/hashset/HashSet.java @@ -0,0 +1,65 @@ + +package com.thealgorithms.datastructures.hashset; + +/** + * Example usage: + *
+ * HashSet set = new HashSet();
+ * set.add(5);
+ * set.add(10);
+ * System.out.println(set.contains(5)); // true
+ * set.remove(5);
+ * System.out.println(set.contains(5)); // false
+ * 
+ */ + +import java.util.LinkedList; + +/** + * A simple implementation of a HashSet for integers using separate chaining. + * + * See: https://en.wikipedia.org/wiki/Hash_table + */ +public class HashSet { + private static final int INITIAL_CAPACITY = 16; + private LinkedList[] buckets; + private int size; + + @SuppressWarnings("unchecked") + public HashSet() { + buckets = (LinkedList[]) new LinkedList[INITIAL_CAPACITY]; + for (int i = 0; i < INITIAL_CAPACITY; i++) { + buckets[i] = new LinkedList(); + } + size = 0; + } + + private int hash(int key) { + return Math.abs(key) % buckets.length; + } + + public void add(int key) { + int idx = hash(key); + if (!buckets[idx].contains(key)) { + buckets[idx].add(key); + size++; + } + } + + public boolean contains(int key) { + int idx = hash(key); + return buckets[idx].contains(key); + } + + public void remove(int key) { + int idx = hash(key); + if (buckets[idx].remove((Integer) key)) { + size--; + } + } + + public int size() { + return size; + } +} +