Map.java
public interface Map<K,V> {
public V put(K k,V v);
public V get(K k);
public int size();
interface Entry<K,V>{
K getKey();
V getValue();
V setValue(V v);
}
}
HashMap.java
public class HashMap<K,V> implements Map<K,V>{
Node<K,V>[] array = null;
private static int defaultLength = 16;
private static double factor = 0.75D;
private int size;
@Override
public V put(K k, V v) {
if(array==null){
array = new Node[defaultLength];
}
int index = position(k,defaultLength);
if(size>defaultLength*factor){
resize();
}
Node<K,V> node = array[index];
if(node == null){
array[index] = new Node<K,V>(k,v,null);
size++;
}
return null;
}
private void resize(){
Node<K,V>[] temp = new Node[defaultLength << 1];
Node<K,V> node = null;
for(int i = 0;i<array.length;i++){
node = array[i];
while (node!=null){
int index = position(node.getKey(),temp.length);
Node<K,V> next = node.next;
node.next=temp[index];
temp[index] = node;
node = next;
}
}
array = temp;
defaultLength = temp.length;
temp=null;
}
private int position(K k,int length){
int code = k.hashCode();
return code%(length-1);
}
@Override
public V get(K k) {
if(array!=null){
int index=position(k,defaultLength);
Node<K,V> node = array[index];
while (node!=null){
if(node.getKey()==k){
return node.getValue();
}else {
node = node.next;
}
}
}
return null;
}
@Override
public int size() {
return size;
}
static class Node<K,V> implements Entry<K,V>{
K key;
V value;
Node<K,V> next;
public Node(K key,V value,Node<K,V> next){
super();
this.key = key;
this.value = value;
this.next = next;
}
@Override
public K getKey() {
return this.key;
}
@Override
public V getValue() {
return this.value;
}
@Override
public V setValue(V v) {
V oldValue = this.value;
this.value=v;
return oldValue;
}
}
}
测试Test.java
public class Test {
public static void main(String[] args){
Map<String,String> map = new HashMap<>();
map.put("u","3");
System.out.println(map.get("u"));
}
}
结果