手写实现HashMap的put和get方法
interface MyMap < K , V > {
V put ( K key, V value) ;
V get ( K key) ;
}
public class MyHashMap < K , V > implements MyMap < K , V > {
private static final int INIT_CAPACITY = 16 ;
private static final double LOAD_FACTORY = 0.75f ;
private int initcapacity = 0 ;
private double loadfactory = 0f ;
private Entry < K , V > [ ] table = null ;
public MyHashMap ( ) {
this . loadfactory = LOAD_FACTORY;
this . initcapacity = INIT_CAPACITY;
table = new Entry [ this . initcapacity] ;
}
public MyHashMap ( int initcapacity, double loadfactory) {
this . initcapacity = initcapacity;
this . loadfactory = loadfactory;
table = new Entry [ this . initcapacity] ;
}
private int hash ( K key) {
int h;
return key == null ? 0 : Math . abs ( h = key. hashCode ( ) ) ^ ( h>>> 16 ) ;
}
private boolean equ ( Object a, Object b) {
return ( a == b) ;
}
@Override
public V put ( K key, V value) {
int index = hash ( key) % initcapacity;
if ( table[ index] != null ) {
Entry < K , V > e = table[ index] ;
Entry < K , V > e2 = null ;
while ( e != null ) {
if ( hash ( e. key) == hash ( key) && equ ( e. key, key) ) {
e. val = value;
return value;
}
e2 = e;
e = e. next;
}
e2. next = new Entry < > ( key, value, null , index) ;
} else {
Entry < K , V > e = new Entry < > ( key, value, null , index) ;
table[ index] = e;
}
return value;
}
@Override
public V get ( K key) {
int index = hash ( key) % initcapacity;
Entry < K , V > e = table[ index] ;
if ( e == null ) {
return null ;
}
while ( e != null ) {
if ( e. getKey ( ) == null && key == null || hash ( e. getKey ( ) ) == hash ( key) && e. getKey ( ) . equals ( key) ) {
return e. getValue ( ) ;
}
e = e. next;
}
return null ;
}
public static void main ( String [ ] args) {
MyMap < String , Object > map = new MyHashMap < > ( ) ;
map. put ( "name" , "zuoshen" ) ;
map. put ( "age" , 23 ) ;
map. put ( "weight" , 75 ) ;
map. put ( null , "zuozhen2" ) ;
System . out. println ( map. get ( "name" ) ) ;
System . out. println ( map. get ( "age" ) ) ;
System . out. println ( map. get ( "weight" ) ) ;
System . out. println ( map. get ( null ) ) ;
map. put ( "name" , "zuozhen1" ) ;
System . out. println ( map. get ( "name" ) ) ;
}
}
class Entry < K , V > {
K key;
V val;
Entry < K , V > next;
int index;
Entry ( K key, V val, Entry < K , V > next, int index) {
this . key = key;
this . val = val;
this . next = next;
this . index = index;
}
public K getKey ( ) {
return key;
}
public V getValue ( ) {
return val;
}
public Entry < K , V > getNext ( ) {
return next;
}
}