4. Implement a simple HashMap and Its Principle
4.1 In the put () method:
1) First, the key-value pair hash code to be inserted is obtained through the key, and the hash code is used as the index to find the elements corresponding to the key in the array bucket.
2) encapsulate the key-value pair to be inserted into an object of the class implementing the Map. Entry interface.
3) in operation 1) check whether there are elements that are the same as the key-value pair to be inserted in the array element (also a sort list). If yes, update the key-value pair array element to be inserted if no value exists.
4.2 In the get () method
1) First, obtain the key-value pair hash code to be searched through the key, and use the hash code as the index to find the elements corresponding to the key in the array bucket.
2) encapsulate the key-value pair to be searched into an object of the class implementing the Map. Entry interface.
3) in operation 1) check whether there are elements that are the same as the key-value pair to be inserted in the array element (also a sort list). If yes, return the value corresponding to the key. If no value exists, return a null value.
4.3 one instance
- ImportJava. util .*;
- /**
- * The MPair class implements Map. Entry.
- */
- ClassMPair
- Implements Map. Entry,Comparable{
- ObjectKey, value;
- MPair (ObjectK,ObjectV ){
- Key = k;
- Value = v;
- }
- Public ObjectGetKey (){ReturnKey ;}
- Public ObjectGetValue (){ReturnValue ;}
- Public ObjectSetValue (ObjectV ){
- ObjectResult = value;
- Value = v;
- ReturnResult;
- }
- /**
- * When comparing two MPair objects, their key values are compared.
- */
- Public BooleanEquals (ObjectO ){
- ReturnKey. equals (MPair) o). key );
- }
- Public IntCompareTo (ObjectRv ){
- Return(((Comparable) Key). compareTo (MPair) rv). key ));
- }
- }
- ClassSimpleHashMapExtends AbstractMap{
- Private Final Static IntSZ = 997;
- Private Shortlist[] Bucket =New Shortlist[SZ];
- /**
- * Encapsulate the key and value into the implementation class of Map. Entry and insert it into the array.
- */
- Public ObjectPut (ObjectKey,ObjectValue ){
- ObjectResult =Null;
- // Obtain the key-value pair hash code to be inserted through the key
- IntIndex = key. hashCode () % SZ;
- If(Index <0) index =-index;
- If(Bucket [index] =Null)
- Bucket [index] =New Shortlist();
- & Nb