Learn-dsa..in 30 days!



























CC-20 : Implement a basic HashSet implementation POC.

Description:

Implement a basic HashSet POC. Implement methods such as hash(), add(), remove(), contains() which demonstrate HashSet functionalities.

Test cases and expected outputs:

Input Parameters Expected outputs
DHashset sp=new DHashset(); sp.add(700); sp.add(250);
sp.contains(700); true
sp.remove(250);
sp.contains(250); false

Pseudocode:

Create a java class called DHashSet.
In DHashSet initialize an int member variable named capacity and set it to 10000.
In DHashSet initialize a member variable boolean array named set with size equal to capacity. Note by default all indexes of set are set to false indicating our HashSet is empty.
Create a method hash() that takes a key as input:
Return basic hash calculated by key%capacity.
Create a method add() that takes a key as input:
Set hashkey=hash(key).
Set set[hashkey] to true.
Now set[hashkey] being true means we have stored key in set.
Create a method remove() that takes a key as input:
o Set hashkey=hash(key).
o Set set[hashkey] to false.
o Now set[hashkey] being false means key is now no longer stored in set.
Create a method contains() that takes a key as input:
Set hashkey=hash(key).
if set[hashkey] is true, it means key is stored in hash. If set[hashkey] is false, it means key is not stored in hash. Return set[hashkey].

Code:

public class DHashset {

private int capacity=10000;
private boolean[] set= new boolean[capacity];


public int hash(int key) {
	return key%capacity;
}

public void add(int key) {
	int hashkey=hash(key);
	set[hashkey]=true;
}

public void remove(int key) {
	int hashkey=hash(key);
	set[hashkey]=false;
}


public boolean contains(int key) {
	int hashkey=hash(key);
	return set[hashkey];
}
}

Click here to download and run code and test cases !