Home  >  Article  >  Java  >  The difference between HashMap and LinkedHashMap in java

The difference between HashMap and LinkedHashMap in java

王林
王林Original
2019-11-18 14:19:345304browse

The difference between HashMap and LinkedHashMap in java

HashMap

HashMap is the most commonly used Map. It stores data according to the HashCode value of the key. Its value can be obtained directly according to the key. It has The access speed is very fast, and the order during traversal is completely random. HashMap only allows one key to be Null and allows multiple values ​​to be Null.

Features: Completely random

Advantages: Random access, fast value acquisition

Disadvantages: Multiple threads writing HashMap at the same time may cause data inconsistency. If synchronization is required, use Collection's synchronizedMap method or use ConcurrentHashMap

LinkedHashMap

LinkedHashMap is a subclass of HashMap that saves the insertion of records The order is different from the random traversal of HashMap. When traversing with Iterator, the record obtained first must be inserted first, similar to OrderedDict in python.

The traversal speed will be slower than HashMap, but there is an exception: when the capacity of HashMap is large and the actual data is very small, because the traversal speed of HashMap is related to its capacity, while LinkedHashMap is only related to the actual amount of data. related.

TreeMap

TreeMap implements the SortMap interface and can sort the records it saves by key. The default is ascending order by key. You can also specify a sorting comparator to traverse the TreeMap When , the records obtained are sorted by key.

Select Map based on data

Generally, what we use most is HashMap. To insert, delete and locate elements in Map, HashMap is the best choice. . But if you want to iterate over keys in natural order or custom order, then TreeMap will be better. If you need the output order to be the same as the input, you can use LinkedHashMap, which can also be arranged in reading order.

Recommended tutorial: Java tutorial

The above is the detailed content of The difference between HashMap and LinkedHashMap in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn