Why HashMap and LinkedHashMap? First, these two types of data structures are commonly used in Java Coder. Second, these two types of data structures are the most appropriate to illustrate the structural relationship between linked lists and arrays. What is a hash value? A hash value is converted from a binary value to a fixed length binary value using the hash algorithm.

How does the Map structure we typically use store data? It carries on the data storage through the array and the linked list combination form. As we know from the previous section, the query speed of linear tables is relatively fast, and the insertion speed of linked lists is relatively fast. Map is a combination of the two. Data structures are stored in the form of arrays in the periphery and linked lists in the interior, and fast addressing and insertion is achieved through hash values. The following shows a common data structure in hash tables — zipper method.

This form of storage structure is the data structure of HashMap we commonly 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 stores data elements internally in the form of key-value pairs.

This diagram shows the data structure of LinkedHashMap. Unlike HashMap, the data elements in its list are stored in an ordered order. One of the biggest differences is that LinkedHashMap is a bidirectional list, and if the data structure is complex when used (e.g. A layer contains a layer of data objects), for more efficient use of LinkedHashMap, you can use the following code to solve the LinkedHashMap thread synchronization problem.

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

Similarly, HashMap thread is out of sync, can also use the Collections. The synchronizedMap () method to make thread safety, increase after Jdk1.8 ConcurrentHashMap instance is thread-safe, Use this as much as possible for higher versions.

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

More exciting to wechat public number [Lao Wang said programming] >>>