The data structure that programmers must know: HashMap and LinkedHashMap

The data structure that programmers must know: HashMap and LinkedHashMap

Why say HashMap and LinkedHashMap? First: These two data structures are frequently used data structures in Java Coder. Second: These two structures are the most suitable to illustrate the structural relationship between linked lists and arrays. Before we start, we must first understand a concept, what is a hash value? The hash value refers to the conversion of a binary value into a fixed-length binary value through the hash algorithm.

In what way does the Map structure we usually use store data? It stores data through the combination of an array and a linked list. In the description of the previous section, we know that the query speed of the linear table is relatively fast, and the insertion speed of the linked list is relatively fast. Map is a combination of the two. The data structure uses an array outside and a linked list inside to store data. The hash value is used to achieve fast addressing and relatively fast insertion. Let's take a look at the common hash tables through the picture. Data structure display-zipper method.

This form of storage structure is the data structure of HashMap that we usually use. As shown in the figure, 0~12 form an array, and each position stores a linked list, and each data object in the linked list is passed through Data elements are stored in the form of key-value pairs.

This picture shows the data structure diagram of LinkedHashMap. Unlike HashMap, the data elements in its linked list are stored in an orderly manner. The biggest difference is that LinkedHashMap is a doubly linked list. If the data structure is complicated (for example, one layer contains data objects in one layer) and high efficiency is required, it is best to use LinkedHashMap, which can be solved by the following code LinkedHashMap thread is not synchronized.

Map<String,Object> map = Collections.synchronizedMap(new LinkedHashMap<String,Object>());

Similarly, HashMap is also thread-unsynchronized. You can also use the Collections.synchronizedMap() method to make thread-safe. The ConcurrentHashMap instance added after Jdk1.8 is thread-safe. Use this method as much as possible if you have a higher version.

Map<String, Object> map2 = new ConcurrentHashMap<String, Object>();

More exciting go to WeChat public account [Lao Wang said programming] >>>