public class CustomHashMap<K, V> {
private Entry<K, V>[] table; //Array of Entry
private int capacity = 4; //Initial Capacity of HashMap
static class Entry<K, V> {
K key;
V value;
Entry<K, V> next;
public Entry(K key, V value, Entry<K, V> next) {
this.key = key;
this.value = value;
this.next = next;
}
}
@SuppressWarnings("unchecked")
public CustomHashMap() {
table = new Entry[capacity];
}
public void put(K newKey, V data) {
if(newKey == null) {
return; // does not allow to store null
}
//Calculate hash of Key
int hash = hash(newKey);
//Create new entry
Entry<K, V> entry = new Entry<K, V>(newKey, data, null);
//If table location doesn't contain any entry, store entry there.
if(table[hash] == null) {
table[hash] = entry;
} else {
Entry<K, V> previous = null;
Entry<K, V> current = table[hash];
while (current != null) { // reached last entry of bucket
if(current.key.equals(newKey)) {
if(previous == null) { //node has to be inserted on first of Bucket
entry.next = current.next;
table[hash] = entry;
return;
} else {
entry.next = current.next;
previous.next = entry;
}
}
previous = current;
current = current.next;
}
previous.next = entry;
}
}
public V get(K key) {
int hash = hash(key);
if(table[hash] == null) {
return null;
} else {
Entry<K, V> temp = table[hash];
while(temp != null) {
if(temp.key.equals(key)){
return temp.value; // return value corresponding to key
}
temp = temp.next;
}
return null;
}
}
public boolean remove(K deleteKey) {
int hash = hash(deleteKey);
if(table[hash] == null){
return false;
} else {
Entry<K, V> previous = null;
Entry<K, V> current = table[hash];
while(current != null){
if(current.key.equals(deleteKey)) {
if(previous == null) {
table[hash] = table[hash].next; // delete first entry node
return true;
} else {
previous.next = current.next;
return true;
}
}
previous = current;
current = current.next;
}
return false;
}
}
public void printMap() {
for (int i = 0; i < table.length; i++) {
if(table[i] != null) {
Entry<K, V> entry = table[i];
while (entry != null) {
System.out.println("{" + entry.key + "=" + entry.value + "}");
entry = entry.next;
}
}
}
}
private int hash(K key) {
return Math.abs(key.hashCode()) % capacity;
}
}