Skip to content

Add HashSet data structure implementation for integers (#6304) #6402

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@

package com.thealgorithms.datastructures.hashset;

/**
* Example usage:
* <pre>
* 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
* </pre>
*/

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<Integer>[] buckets;
private int size;

@SuppressWarnings("unchecked")
public HashSet() {
buckets = (LinkedList<Integer>[]) new LinkedList[INITIAL_CAPACITY];
for (int i = 0; i < INITIAL_CAPACITY; i++) {
buckets[i] = new LinkedList<Integer>();
}
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;
}
}

Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy