Detailed explanation of Java HashMap, treemap and LinkedHashMap
Detailed explanation of Java HashMap, treemap and LinkedHashMap
During the interview this morning, I asked about Java and map. I remember the content related to HashMap and treemap wrong. I came back and tried several demos to understand it
Map is different from list. The bottom layer stores data in the form of key value pairs Entry is an internal sub item. Different implementations of map have different indexing schemes for key value pairs. HashMap itself uses hash function to index key values. We cannot determine the order of the last key values
However, an interesting phenomenon is that when integer is used as the key value pair, when the number of digits is 1, the key values are arranged from small to large, and there may be problems when the number of digits rises to two
There is a balance tree inside treemap to store the key value index. Treemap sorts the key values according to the comparison function. I speculate that there may be an AVLTree inside
A feature of LinkedHashMap is that key value pairs are sorted according to the insertion order. If there is repeated insertion, it is recorded in the order of the first insertion. An online saying is that there are double hashes inside the structure
One solves the sequence problem and the other solves the storage problem. The correctness needs to be confirmed
HashMap and treemap are the two most commonly used map structures. Generally speaking, HashMap has high efficiency and is the most common. Treemap will be used only if we need orderly key values
Thank you for reading, hope to help you, thank you for your support to this site!