Recently busy, want to study with you and discuss some of the Java source code and its implementation of the data structure,
Not a high-level thing, an interested casual look
1. Why map, take HashMap as an example
Many times we have this requirement, we need to store the data in a key-value pair, based on the key to get the value (value can be a simple value, or it can be a custom object)
Of course, the object array can also be used to achieve this purpose, the search can iterate through the array, compare the keyword to get the corresponding value
In terms of performance, traversing large arrays consumes performance
In terms of API ease of use, you need to implement your own lookup logic
So it's necessary to use HashMap.
2. What is the data structure of HashMap?
I have been very curious about the internal structure of HashMap, after reading the source found that he was a hash implementation, that is, based on hashcode
The general idea is this
2.1 First create an array to access the data, suppose we define a object[] table to access the value of map
This is easy to understand, where does key exist? For the moment I don't want to store key
2.2 The hashcode of key is converted into an integer by a certain algorithm.
Index, the value range of this index must be 0=<index<table.length, and then I use it as the subscript for the array element
For example, perform this operation: table[index] = value;
The problem with this storage is solved
2.3 How do I get this value through key?
This is too simple, first get the key hashcode, and then through the same algorithm to derive the element subscript index
Then value = Table[index]
The simple Hashtable implementation is as follows
Public classSimplehashmap {Privateobject[] table; PublicSimplehashmap () {table=NewObject[10]; } Publicobject get (Object key) {intindex = indexfor (hash (Key.hashcode ()), 10); returnTable[index]; } Public voidput (object key, Object value) {intindex = indexfor (hash (Key.hashcode ()), 10); Table[index]=value; } /*** 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); } Public Static voidMain (string[] args) {Simplehashmap HashMap=NewSimplehashmap (); Hashmap.put ("Key", "value"); System.out.println (Hashmap.get ("Key")); }}
This simple example describes the process of hashing the implementation of HashMap
But still immature, I found that there are at least two of the following questions
1. The size of the HASHMAP is fixed
2. If the index of different key through Hashcode is the same, this situation is exist, how to solve?
See series Article Two
Come with me read the hashmap of Java source Code (a)