1.接口类
public interface SelfMap<K,V> {
V get(K k);
V put(K k,V v);
int size();
interface Entry<K,V>{
K getkey();
V getValue();
}
}
- HashMap
import java.util.ArrayList;
import java.util.List;
public class SelfHashMap<K,V> implements SelfMap<K,V> {
static final int DEFAULT_INITIAL_CAPACITY=1<<4;//初始容量
static final float DEFAULT_LOAD_FACTOR=0.75f;//载荷因子
private int initialCapacity;
private float loadfactor;
private Node<K,V>[] table;
private int size;
public SelfHashMap(){
this(DEFAULT_INITIAL_CAPACITY,DEFAULT_INITIAL_CAPACITY);
}
public SelfHashMap(int initialCapacity,float loadfactor){
this.initialCapacity=initialCapacity;
this.loadfactor=initialCapacity;
table=new Node[initialCapacity];
}
private int hash(K key){
int h;
return (key==null)?0:(h=key.hashCode())^(h>>>16);
}
public V put(K k,V v){
V oldValue=null;
if(size>=initialCapacity*loadfactor){
resize();
}
int hashcode=hash(k);
int index=hashcode&(initialCapacity-1);
if(table[index]==null){
table[index]=new Node<>(hashcode,k,v,null);
size++;
}else{
Node<K,V> nextNode=table[index];
Node<K,V> pre=null;
while(nextNode!=null){
if(nextNode.hash==hashcode&&(k==nextNode.getkey()||k.equals(nextNode.getkey()))){
oldValue=nextNode.getValue();
nextNode.value=v;
return oldValue;
}
pre=nextNode;
nextNode=nextNode.next;
}
pre.next=new Node<>(hashcode,k,v,null);
}
return oldValue;
}
private void resize(){
int newSize=initialCapacity<<1;
Node<K,V>[] newTable=new Node[newSize];
initialCapacity=newSize;
rehash(newTable);
}
private void rehash(Node<K,V>[] newTable){
List<Node<K,V>> entryList=new ArrayList<>();
for(Node<K,V>node:table){
if(node!=null){
entryList.add(node);
while(node.next!=null){
entryList.add(node.next);
node=node.next;
}
}
}
table=newTable;
size=0;
for(Node<K,V>node:entryList){
put(node.getkey(),node.getValue());
}
}
public V get(K k){
int hashCode=hash(k);
int index=hash(k)&(initialCapacity-1);
if(table[index]==null){
return null;
}else{
Node<K,V>node=table[index];
while(node!=null){
if(node.hash==hashCode&&(k==node.getkey()||k.equals(node.getkey()))){
return node.value;
}else{
node=node.next;
}
}
}
return null;
}
public int size(){
return size;
}
}
class Node <K,V> implements SelfMap.Entry<K,V>{
public int hash;
public K key;
public V value;
public Node<K,V> next;
public Node(int hash,K key,V value,Node<K,V>next){
this.hash=hash;
this.key=key;
this.value=value;
this.next=next;
}
public K getkey(){
return key;
}
public V getValue(){
return value;
}
}