JDK1.7:数组+链表
JDK1.8:数组+链表+红黑树
Map接口
public interface Map<K,V> {
V put(K k,V v);
V get(K k);
int size();
interface Entry<K,V>{
K getKey();
V getValue();
}
}
HashMap类
public class HashMap<K,V> implements Map<K,V> {
Entry<K,V>[] table=null;
int size=0;
public HashMap() {
table = new Entry[16];
}
@Override
public V put(K k, V v) {
int index=hash(k);
Entry<K, V> entry = table[index];
if(entry==null){
table[index]=new Entry<>(k,v,index,null);
size++;
}
else {
table[index]=new Entry<>(k,v,index,entry);
size++;
}
return table[index].getValue();
}
private int hash(K k){
int index=k.hashCode()%16;
return index>=0?index:Math.abs(index);
}
@Override
public V get(K k) {
int index=hash(k);
Entry<K, V> entry = findValue(table[index], k);
return entry==null?null:entry.getValue();
}
public Entry<K,V> findValue(Entry<K,V> entry,K k){
if(k.equals(entry.getKey())||k==entry.getKey()){
return entry;
}else {
if(entry.next!=null){
return findValue(entry.next,k);
}
return null;
}
}
@Override
public int size() {
return size;
}
class Entry<K,V> implements Map.Entry<K,V>{
K k;
V v;
int index;
Entry<K,V> next;
public Entry(K k, V v, int index, Entry<K, V> next) {
this.k = k;
this.v = v;
this.index = index;
this.next = next;
}
@Override
public K getKey() {
return k;
}
@Override
public V getValue() {
return v;
}
}
}