Get the App
SLTechnology News&Howtos  ›  Development  › 

What do you need to consider when using Map

Shulou Source: shulou.com Published: 2022-06-03 00:44:39 09月11日 Update

This article mainly explains "what should be considered when using Map". Friends who are interested might as well take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what to consider when using Map.

First of all, before using Map, let's consider the first question why we should use Map as a data structure. In my work, I will think of the scenarios where Map is used:

Group the data according to certain rules and use Key as the identification of the grouping

Cache, use Key as an index to find data.

After confirming that you want to use Map, you need to consider which Map to use. HashMap is usually the first to think of, and the most commonly used. However, we need to pay attention to two places, whether there are requirements for thread safety and order.

Thread safety:

If there are no concurrent writes, you can use HashMap directly.

If there are concurrent writes, you need to use thread-safe ConcurrentHashMap.

Order:

If you want to sort by Key, you should use TreeMap.

If you want to sort in the order in which you write, you can use LinkedHashMap. If you want to implement LRU,LinkedHashMap, it is the best choice.

If both ordering and thread safety are required, it is important to note that neither TreeMap nor LinkedHashMap is thread safe. For TreeMap, you can use methods such as Collections.synchronizedSortedMap, synchronized, and locking to synchronize. Similarly, LinkedHashMap can also use Collections.synchronizedMap, synchronized, and locks to ensure thread safety.

In the case of using HashMap, you can use WeakHashMap if you are going to use it as a cache and you want the cache to be cleaned automatically.

After determining the type of Map, the final consideration is whether you need to specify the initialization size.

When using HashMap, ConcurrentHashMap, and LinkedHashMap, if we can know the number of storage elements in advance, we can calculate the initialization size according to the following formula and pass it into the constructor to avoid unnecessary expansion.

Summary:

Whether to use Map or not

What type of Map is appropriate to use

Whether the initialization size can be specified.

At this point, I believe you have a deeper understanding of "what you need to consider when using Map". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Safe threaded ordered size data orderability cache content case method type grouping learning sorting appropriate practical deeper further two elements Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi vpn MariaDB Microsoft Shulou Information