1.HasMap Custom Base version
packagecom.test.collection;/*** Custom Implementation Map function * Map: Store key value pairs, find corresponding Value object according to key object *@authorChenx **/ public classMyMap001 {entry[] arr=Newentry[999]; intsize; public voidput (Object key,object Value) {Entry e=NewEntry (key,value); //Resolve key duplication of processing, followed by direct overwrite for(inti=0;i<size;i++){ if(arr[i].key.equals (key)) {arr[i].value=value; return; }} arr[size++]=e; } publicObject Get (object Key) { for(inti=0;i<size;i++){ if(arr[i].key.equals (key)) {returnarr[i].value; } } return NULL; } public BooleanContainsKey (Object Key) { for(inti=0;i<size;i++){ if(arr[i].key.equals (key)) {return true; } } return false; } public intsize () {returnsize; } public Static voidmain (string[] Args) {MyMap001 map=NewMyMap001 (); Map.put ("a", "zhang san"); Map.put ("a", "john doe"); Map.put ("c", "harry"); //Map.Remove (2);System.out.println (map.get ("a")); System.out.println (map.size ()); }}classEntry{Object key; Object value; publicEntry (object key, object Value) {Super(); this. Key =key; this. Value =value; }}
2.HASMAP Custom Upgrade Version
packagecom.test.collection;Importjava.util.LinkedList;/*** Custom Implementation Map function (upgrade Version) * map: Store key value pairs, find corresponding Value object according to Key object * * 1. Improve query efficiency and avoid looping through MyMap002: array + linked list * * HashMap: underlying implementation (array + linked list), linked list objects, objects Save Key,value * *@authorChenx **/ public classMyMap002 {linkedlist[] arr=Newlinkedlist[999]; intsize; public voidput (Object key,object Value) {Entry2 e=NewEntry2 (key,value); inthas=Key.hashcode (); has= has<0?-has:has; intA =has%arr.length; if(arr[a] = =NULL) {linkedlist list=NewLinkedList (); arr[a]=list; List.add (e); }Else{linkedlist List=arr[a]; for(intI=0;i<list.size (); i++) {Entry2 E1=(Entry2) List.get (i); if(e1.key.equals (key)) {e1.value= value;//repeat to overwrite return; }} Arr[a].add (e); } } publicObject Get (object Key) {inthas=Key.hashcode (); has= has<0?-has:has; intA =has%arr.length; if(arr[a]! =NULL) {linkedlist list=arr[a]; for(intI=0;i<list.size (); i++) {Entry2 e=(Entry2) List.get (i); if(e.key.equals (key)) {returne.value; } } } return NULL; } public Static voidmain (string[] Args) {MyMap002 map=NewMyMap002 (); Map.put ("a", "zhang san"); Map.put ("a", "john doe"); Map.put ("c", "harry"); //Map.Remove (2);System.out.println (map.get ("a")); //System.out.println (map.size ()); }}classEntry2{Object key; Object value; publicEntry2 (object key, object Value) {Super(); this. Key =key; this. Value =value; }}
Java Collection Chapter Five: HashMap