Implement HashMap with array
1. Implement Put and Delete for Hashmap
2. Use Array to store each Entry
3. Use chain linkedlist to handle collision
Insert Node:
If arr contains null, then insert the new key and data, increase count
If arr contains some nodes, then check whether the new key is in the list
If the key is in the list, update the data, done
If the key is Not in the list, goto the last node,
insert the key and data to the end of the list
TODO: add contains method, increase the size of array if the number of elements is
greater than the max value.
class Entry{
public String key;
public Object value;
public Entry next;
public Entry(String key, Object value){
this.key = key;
this.value = value;
}
}
class Hash{
public Entry[] arr;
public int max;
public int count = 0;
public Hash(int max){
this.max = max;
arr = new Entry[max];
}
public Node get(String key){
int hash = key.hashCode() % max;
return (Node)arr[hash].value;
}
public void delete(String key){
if(key != null){
int hash = key.hashCode() % max;
Entry curr = arr[hash];
if(curr != null){
Entry prev = null;
while(curr != null){
if(curr.key == key)
break;
else{
prev = curr;
curr = curr.next;
}
}
if(prev == null){
arr[hash] = curr.next;
count--;
}else{
if(curr != null){
prev.next = curr.next;
count--;
}
}
}
}
}
public void put(String key, Node node){
if(count < max){
int hash = key.hashCode() % max;
Entry curr = arr[hash];
if(curr == null){
arr[hash] = new Entry(key, node);
count++;
}
else{
Entry prev = null;
while(curr != null){
if(curr.key.equals(key)){
// Replace with new value
curr.value = node;
break;
}
else{
prev = curr;
curr = curr.next;
}
}
// No key is found
if(curr == null){
prev.next = new Entry(key, node);
count++;
}
}
}
}
}