import java.util.ArrayList;
import java.util.List;
public class HashMapImpl<K, V> {
private class Tuple {
private K key;
private V value;
}
private class LNode<U> {
LNode<U> next;
U value;
public LNode(U value, LNode<U> next) {
this.value = value;
this.next = next;
}
}
private int maxSize = 100;
private List<LNode<Tuple>> store = new ArrayList<>();
private int size = 0;
public HashMapImpl() {
for(int i = 0; i < maxSize; i++) {
store.add(new LNode<Tuple>(null, null));
}
}
public V get(K key) {
LNode<Tuple> head = store.get(getHash(key));
LNode<Tuple> current = head.next;
while(current != null) {
if(current.value.key.equals(key)) {
return current.value.value;
}
current = current.next;
}
return null;
}
private int getHash(K key) {
return key.hashCode() % maxSize;
}
public boolean contains(K key) {
LNode<Tuple> head = store.get(getHash(key));
LNode<Tuple> current = head.next;
while(current != null) {
if(current.value.key.equals(key)) {
return true;
}
current = current.next;
}
return false;
}
public void put(K key, V value) {
LNode<Tuple> head = store.get(getHash(key));
LNode<Tuple> current = head.next;
if(current == null) {
Tuple t = new Tuple();
t.key = key;
t.value = value;
head.next = new LNode<Tuple>(t, null);
size ++;
return;
}
while(current.next != null) {
if(current.value.key.equals(key)) {
current.value.value = value;
return;
}
current = current.next;
}
Tuple t = new Tuple();
t.key = key;
t.value = value;
current.next = new LNode<Tuple>(t, null);
size ++;
}
V remove(K key) {
LNode<Tuple> head = store.get(getHash(key));
LNode<Tuple> current = head.next;
while(current.next != null) {
if(current.next.value.key.equals(key)) {
V oldValue = current.next.value.value;
current.next = current.next.next;
size --;
return oldValue;
}
current = current.next;
}
return null;
}
int size() {
return size;
}
public static void main(String[] args) {
HashMapImpl<Integer, Integer> hashmap = new HashMapImpl<>();
for(int i = 0; i < 1000; i++) {
hashmap.put(i, i);
}
System.out.println(hashmap.get(30));
System.out.println(hashmap.get(300));
System.out.println(hashmap.get(3000));
System.out.println(hashmap.remove(300));
System.out.println(hashmap.contains(300));
System.out.println(hashmap.size());
System.out.println(hashmap.get(299));
System.out.println(hashmap.get(300));
System.out.println(hashmap.get(301));
hashmap.put(300, 300);
System.out.println(hashmap.contains(300));
System.out.println(hashmap.size());
System.out.println(hashmap.get(299));
System.out.println(hashmap.get(300));
System.out.println(hashmap.get(301));
}
}