import java.util.LinkedList;
public class MyHashMap<K,V> {
private int capacity;
private float loadFactor;
private LinkedList<Node>[] array;
private int size;
public MyHashMap(int capacity, float loadFactor) {
this.capacity = capacity;
this.loadFactor = loadFactor;
array = new LinkedList[capacity];
size = 0;
}
public V get(K key) {
int index = key.hashCode() % capacity;
LinkedList<Node> list = array[index];
if (list != null) {
for (Node node : list) {
if (node.key.equals(key)) {
return node.value;
}
}
}
return null;
}
public void put(K key, V value) {
int index = key.hashCode() % capacity;
LinkedList<Node> list = array[index];
if (list == null) {
list = new LinkedList<Node>();
array[index] = list;
}
for (Node node : list) {
if (node.key.equals(key)) {
node.value = value;
return;
}
}
list.add(new Node(key, value));
size++;
if (size / (float)capacity > loadFactor) {
resize();
}
}
private void resize() {
capacity = capacity * 2;
LinkedList<Node>[] newArray = new LinkedList[capacity];
for (LinkedList<Node> list : array) {
if (list != null) {
for (Node node : list) {
int index = node.key.hashCode() % capacity;
LinkedList<Node> newList = newArray[index];
if (newList == null) {
newList = new LinkedList<Node>();
newArray[index] = newList;
}
newList.add(node);
}
}
}
array = newArray;
}
private class Node {
K key;
V value;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
}
}