1 Importjava.util.ArrayList;2 Importjava.util.List;3 4 classEntry<k, v> {5 K key;6 V value;7 8 Entry (K key, V value) {9 This. Key =key;Ten This. Value =value; One } A } - - Public classMyhashmap<k, v> { the Private Static Final intDefault_size = 20; - Private intSize = 0; - PublicList<entry<k, v>>[] array; - + PublicMyhashmap () { - This. Array =NewList[default_size]; + } A at Private intHash (K key) { - inttemp =Key.hashcode (); - return(Temp & 0x7FFFFFFF)%Array.Length; - } - - Public voidput (K key, V value) { in intIndice =hash (key); - if(Array[indice] = =NULL) { toArray[indice] =NewArraylist<entry<k, v>>(); +Array[indice].add (NewEntry<k, v>(key, value)); -size++; the}Else { * BooleanFind =false; $ for(Entry<k, v>E:array[indice]) {Panax Notoginseng if(E.key = =key) { -E.value =value; theFind =true; + } A } the if(!find) { +Array[indice].add (NewEntry<k, v>(key, value)); -size++; $ } $ } - if(Size >= ARRAY.LENGTH/2) { - rehash (); the } - }Wuyi the PublicV get (K key) { - intIndice =hash (key); Wu if(Array[indice] = =NULL) { - return NULL; About } $ for(Entry<k, v>E:array[indice]) { - if(E.key = =key) { - return(V) e.value; - } A } + return NULL; the } - $ Public BooleanContainsKey (K key) { the intIndice =hash (key); the if(Array[indice] = =NULL) { the return false; the } - for(Entry<k, v>E:array[indice]) { in if(E.key = =key) { the return true; the } About } the return false; the } the + Public intsize () { - returnsize; the }Bayi the Public BooleanIsEmpty () { the returnSize = = 0; - } - the Private voidrehash () { theList<entry<k, v>>[] cur =NewList[2 *Array.Length]; the for(inti = 0; i < Array.Length; i++) { theCur[i] =Array[i]; - } theArray =cur; the } the}
Java HashMap Implementation