File tree Expand file tree Collapse file tree
src/main/java/com/thealgorithms/datastructures/hashset Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments