The Simplehashmap implemented in the previous section, there is no resolution to the conflict, this section we continue in depth
Because the size of the table is limited, and the key collection range is infinite, so hope that the hashcode scattered, there will be more than one key scattered in the same array subscript below,
So we're going to introduce another concept, the key and value into Table[index], the key and value to make an object in the Table[index], and may have more than one, their key corresponds to the same index, but the key itself is different
Now we should talk about how to store the elements scattered in the same array subscript
Can you consider arrays?
You can also consider linked list storage
The source is stored in a linked list, in fact, I do not understand what the difference between these two ways
, it feels almost as efficient in both retrieval and storage,
Retrieval is a way to traverse, and storage can be sequential
Let's leave the question to everyone.
To implement the chained storage approach, we first define a linked list data structure entry:
Public class Entry<k, v> { // store keyfinal K key; // Store Value V value; // stores a pointer to the next node Entry<k, v> next; // hash to store key mappings Final int hash; }
New ways to implement Entryhashmap
Public classEntryhashmap<k, v> { transiententry[] table; transient intsize; Publicv put (K key, V value) {//calculate a new hash inthash =Hash (Key.hashcode ()); //calculate the array of small labels I inti =indexfor (hash, table.length); //Traverse Table[i], if table[i] is not equal to the newly added key, the new join//a value of entry in Table[i], otherwise overwrites the old value with the new value and returns the old value for(entry<k, v> e = table[i]; E! =NULL; E =e.next) {Object k; if(E.hash = = Hash && (k = e.key) = = Key | |Key.equals (k))) {V OldValue=E.value; E.value=value; returnOldValue; }} addentry (hash, key, value, I); return NULL; } Public voidAddEntry (intHash, K key, V value,intBucketindex) {Entry<k, v> e =Table[bucketindex]; //inserting new elements into the front of the listTable[bucketindex] =NewEntry<>(hash, key, value, E); Size++; } /*** Get the corresponding array subscript by hash code and the length of table * *@paramh *@paramlength *@return */ Static intIndexfor (intHintlength) { returnH & (length-1); } /*** A new hash value is calculated by a certain algorithm * *@paramh *@return */ Static intHashinth) {h^= (H >>>) ^ (H >>> 12); returnH ^ (H >>> 7) ^ (H >>> 4); }}
Come with me read the hashmap of Java source Code (II)