Dictionary implementation (4)-using hash method to implement dictionary

Source: Internet
Author: User

1, realize the idea

 Public class Implements Dictionaryinterface<k, v>,        Serializable {

Defining Hasheddictionary.java as the implementation of the hash dictionary, the dictionary implements the following functions:

① adds an element to the dictionary, ② removes the element from the dictionary based on the lookup key, ③ gets the value of a lookup key from the dictionary, and ④ implements an iterator that finds the key key in the dictionary and value

2, for the map dictionary, the first line of code is known: its bottom layer is essentially an array.

The locationused in the third line of code is used to record whether a location in the hash table is being used. Because of the need for conflict handling, when an element is deleted, only the element is deleted as a tag instead of actually deleting the element, the position occupied by that element is essentially already in use. However, there is a problem with the program about this variable.

1     PrivateTableentry<k, v>[] hashTable;2     Private intNumberofentries;//hashtable number of elements3     Private intlocationused;//record the use of Hashtable locations4     Private Static Final intDefault_size = 101;//default size of hash table, prime number5     Private Static Final DoubleMax_load_factor = 0.5;//Loading Factor

3, the constructor, used to generate a hash dictionary instance, from the sixth line of code, it is essentially a new tableentry type of array, and this array is used to store <key,value> index. Tableentry is an inner class of hasheddictionary that encapsulates the actual <key,value> elements, and Hasheddictionary objects represent a dictionary, The basic operation of a dictionary is to manipulate each <key,value> that the tableentry array points to

1      PublicHasheddictionary (inttablesize) {2         /*3 * When the parameter used to construct the hash table is not a prime number, look for the next prime number closest to the parameter4          */5         intPrimesize =Getnextprime (tablesize);6HashTable =NewTableentry[primesize];7numberofentries = 0;8locationused = 0;9}
1 Private class Implements Serializable {2         Private S Entrykey; 3         Private T Entryvalue; 4         Private boolean intable;

4, and then look at the implementation of the iterator

These two internal iterators for the implementation of key and value iterator, only need to implement the method defined in the iterator interface, Then define two functions in Hasheddictionary.java to obtain Keyiterator type and Valueiterator type iterator.

Private class Implements Iterator<k>{... Private class Implements iterator<v>{
 Public Iterator<k> Getkeyiterator () {        returnnew  keyiterator ();    }
Public Iterator<v> Getvalueiterator () { returnnew valueiterator (); }

5, how the hash function is implemented

1     Private int Gethashindex (K key) {2         // The hash code is obtained first, and then the hash code is compressed into an index by% 3         int hashindex = key.hashcode ()% hashtable.length; 4         if (Hashindex < 0) 5             Hashindex = Hashindex + hashtable.length; 6         return Hashindex; 7     }

6, how do I handle conflicts when I add <key,value> elements? The open addressing method of linear detection is used to deal with the conflict.

Call Probe (Index,key) to handle the conflict

1      Public v Add (K key, V value) {2        v oldValue; 3         if (Isfull ()) 4             rehash (); 5         int index = gethashindex (key); 6         index = Probe (index, key); // Linear detection
1 Private intProbeintindex, K key) {2         BooleanFound =false;3         intRemovedstateindex =-1;4          while(!found && (hashtable[index]! =NULL)){5             if(Hashtable[index].isin ()) {6                 if(Key.equals (Hashtable[index].getentrykey ()))7Found =true;8                 Else9Index = (index + 1)%hashtable.length;Ten             } One             Else A{//Save the index at the first location in the deleted state -                 if(Removedstateindex = =-1) -Removedstateindex =index; theIndex = (index + 1)% Hashtable.length;//Linear detection -             } -}//End While -         if(Found | | (Removedstateindex = =-1)) +             returnindex; -         Else +             returnRemovedstateindex; A}

7, because of the possibility of conflict, after a key is generated by the hash function index, the index position may have deposited other elements, then it is how to correctly through the GetValue (K key) method to correctly obtain the value corresponding to key? -----The function of the locate (index, key) function.

1      PublicV GetValue (K key) {2V result =NULL;3         intindex = Gethashindex (key);//get the hash index for the key4index = Locate (index, key);//returns the final indexed address after a conflict is processed5         6         if(Index! =-1)7result =Hashtable[index].getentryvalue ();8         returnresult;9}
1 Private intLocateintindex, K key) {2         BooleanFound =false;3         //when a null element in a hashtable is found, the lookup fails4          while(!found && (hashtable[index]! =NULL)){5             //The value of the key at index is not marked for deletion and the key is the same6             if(Hashtable[index].isin () &&key.equals (Hashtable[index].getentrykey ()))7Found =true;8             Else 9Index = (index + 1)%hashtable.length;Ten         } One         intresult =-1; A         if(found) -result =index; -         returnresult; the}

5th---7 further explanations are needed. Not finished: The complete code will eventually be submitted to GitHub.

Dictionary implementation (4)-using hash method to implement dictionary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.