java 什么时候在java中使用linkedhashmap而不是hashmap?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26623129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:15:29  来源:igfitidea点击:

When to use linkedhashmap over hashmap in java?

javadata-structurestypeshashmaplinkedhashmap

提问by nikhil

What are the practical scenario for choosing among the linkedhashmap and hashmap? I have gone through working of each and come to the conclusion that linkedhashmap maintains the order of insertion i.e elements will be retrieved in the same order as that of insertion order while hashmap won't maintain order. So can someone tell in what practical scenarios selection of one of the collection framework and why?

在linkedhashmap和hashmap中选择的实际场景是什么?我已经完成了每个工作并得出结论,linkedhashmap 维护插入顺序,即元素将按照与插入顺序相同的顺序检索,而 hashmap 不会维护顺序。那么有人可以告诉在哪些实际场景中选择集合框架之一,为什么?

回答by sTg

  1. LinkedHashMapwill iterate in the order in which the entries were put into the map.

  2. nullValues are allowed in LinkedHashMap.

  3. The implementation is not synchronized and uses double linked buckets.

  4. LinkedHashMapis very similar to HashMap, but it adds awareness to the order at which items are added or accessed, so the iteration order is the same as insertion order depending on construction parameters.

  5. LinkedHashMapalso provides a great starting point for creating a Cache object by overriding the removeEldestEntry()method. This lets you create a Cache object that can expire data using some criteria that you define.

  6. Based on linked list and hashing data structures with linked list (think of indexed-SkipList) capability to store data in the way it gets inserted in the tree. Best suited to implement LRU ( least recently used ). LinkedHashMapextends HashMap.

  1. LinkedHashMap将按照条目放入地图的顺序进行迭代。

  2. null中允许值LinkedHashMap

  3. 实现不是同步的,而是使用双链接存储桶。

  4. LinkedHashMap与 非常相似HashMap,但它增加了对添加或访问项的顺序的认识,因此迭代顺序与插入顺序相同,具体取决于构造参数。

  5. LinkedHashMap还为通过覆盖removeEldestEntry()方法创建 Cache 对象提供了一个很好的起点。这使您可以创建一个 Cache 对象,该对象可以使用您定义的某些条件使数据过期。

  6. 基于链表和散列数据结构,具有链表(想想 indexed-SkipList)功能,以将数据插入树中的方式存储数据。最适合实现 LRU(最近最少使用)。 LinkedHashMap延伸HashMap

It maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is,when iterating through a collection-view of a LinkedHashMap, the elements will be returned in the order in which they were inserted. Also if one inserts the key again into the LinkedHashMap, the original order is retained. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted. You can also create a LinkedHashMapthat returns its elements in the order in which they were last accessed.

它按照插入顺序维护映射中条目的链接列表。这允许在地图上进行插入顺序迭代。也就是说,当遍历 a 的集合视图时LinkedHashMap,元素将按照它们被插入的顺序返回。此外,如果再次将密钥插入LinkedHashMap,则保留原始顺序。这允许在地图上进行插入顺序迭代。也就是说,在迭代 a 时LinkedHashMap,元素将按照它们被插入的顺序返回。您还可以创建一个按LinkedHashMap元素上次访问的顺序返回其元素的 。

LinkedHashMap constructors

LinkedHashMap 构造函数

LinkedHashMap( )

This constructor constructs an empty insertion-ordered LinkedHashMap instance with the default initial capacity (16) and load factor (0.75).

此构造函数使用默认初始容量 (16) 和加载因子 (0.75) 构造一个空的插入顺序 LinkedHashMap 实例。

LinkedHashMap(int capacity)

This constructor constructs an empty LinkedHashMap with the specified initial capacity.

此构造函数构造一个具有指定初始容量的空 LinkedHashMap。

 LinkedHashMap(int capacity, float fillRatio)

This constructor constructs an empty LinkedHashMap with the specified initial capacity and load factor.

此构造函数构造一个具有指定初始容量和负载因子的空 LinkedHashMap。

LinkedHashMap(Map m)

This constructor constructs a insertion-ordered Linked HashMap with the same mappings as the specified Map.

此构造函数使用与指定 Map 相同的映射构造一个插入顺序的 Linked HashMap。

LinkedHashMap(int capacity, float fillRatio, boolean Order)

This constructor construct an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering mode.

此构造函数构造一个具有指定初始容量、负载因子和排序模式的空 LinkedHashMap 实例。

Important methods supported by LinkedHashMap

LinkedHashMap 支持的重要方法

 Class clear( )

Removes all mappings from the map.

从地图中删除所有映射。

containsValue(object value )>

Returns true if this map maps one or more keys to the specified value.

如果此映射将一个或多个键映射到指定值,则返回 true。

 get(Object key)

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

返回指定键映射到的值,如果此映射不包含键的映射,则返回 null。

removeEldestEntry(Map.Entry eldest)

Below is an example of how you can use LinkedHashMap:

以下是如何使用 LinkedHashMap 的示例:

Map<Integer, String> myLinkedHashMapObject = new LinkedHashMap<Integer, String>();  
myLinkedHashMapObject.put(3, "car");  
myLinkedHashMapObject.put(5, "bus");  
myLinkedHashMapObject.put(7, "nano");  
myLinkedHashMapObject.put(9, "innova");  
System.out.println("Modification Before" + myLinkedHashMapObject);  
System.out.println("Vehicle exists: " +myLinkedHashMapObject.containsKey(3));  
System.out.println("vehicle innova Exists: "+myLinkedHashMapObject.containsValue("innova"));  
System.out.println("Total number of vehicles: "+ myLinkedHashMapObject.size());  
System.out.println("Removing vehicle 9: " + myLinkedHashMapObject.remove(9));  
System.out.println("Removing vehicle 25 (does not exist): " + myLinkedHashMapObject.remove(25));  
System.out.println("LinkedHashMap After modification" + myLinkedHashMapObject);  

回答by Subhrajyoti Majumder

Shopping Cart is a real life example, where we see cart number against Item we have chosen in order we selected the item. So map could be LinkedHashMap<Cart Number Vs Item Chosen>

购物车是一个真实的例子,我们看到购物车编号与我们选择的项目相对应,以便我们选择该项目。所以地图可以是LinkedHashMap<Cart Number Vs Item Chosen>

回答by ASHWANI KUMAR SINGH BISEN

LinkedHashMapmaintain insertion order of keys, i.e the order in which keys are inserted into LinkedHashMap. On the other hand HashMapdoesn't maintain any order or keys or values. In terms of Performance there is not much difference between HashMapand LinkedHashMapbut yes LinkedHashMap has more memory foot print than HashMapto maintain doubly linked list which it uses to keep track of insertion order of keys.

LinkedHashMap维护键的插入顺序,即键插入的顺序LinkedHashMap。另一方面HashMap,不维护任何顺序或键或值。在性能方面,两者之间没有太大区别HashMapLinkedHashMap但是 LinkedHashMap 比HashMap维护用于跟踪键插入顺序的双向链表具有更多的内存占用。

A HashMaphas a better performance than a LinkedHashMapbecause a LinkedHashMapneeds the expense of maintaining the linked list. The LinkedHashMap implements a normal hashtable, but with the added benefit of the keys of the hashtable being stored as a doubly-linked list. Both of their methods are not synchronized. Let's take a look their API documentation:

AHashMap的性能比 a 更好,LinkedHashMap因为 aLinkedHashMap需要维护链表的费用。LinkedHashMap 实现了一个普通的哈希表,但具有将哈希表的键存储为双向链表的额外好处。他们的两种方法都不同步。我们来看看他们的 API 文档:

The HashMapis a hash table with buckets in each hash slot.

HashMap是一个哈希表,每个哈希槽中都有桶。

API documentation:

API 文档:

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

此实现为基本操作(get 和 put)提供恒定时间性能,假设散列函数在存储桶中正确分散元素。迭代集合视图需要的时间与 HashMap 实例的“容量”(桶的数量)加上它的大小(键值映射的数量)成正比。因此,如果迭代性能很重要,则不要将初始容量设置得太高(或负载因子太低),这一点非常重要。

LinkedHashMapis a linked list implementing the map interface. As said in the API documentation:

LinkedHashMap是一个实现地图接口的链表。正如 API 文档中所说:

Hash table and linked list implementation of the Mapinterface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

接口的哈希表和链表实现Map,具有可预测的迭代顺序。此实现与 HashMap 的不同之处在于它维护一个双向链表,贯穿其所有条目。这个链表定义了迭代顺序,这通常是键被插入到映射中的顺序(插入顺序)。

回答by Arun M R Nair

  • HashMap makes absolutely no guarantees about the iteration order. It can (and will) even change completely when new elements are added.
  • LinkedHashMap will iterate in the order in which the entries were put into the map
  • LinkedHashMap also requires more memory than HashMap because of this ordering feature. As I said before LinkedHashMap uses doubly LinkedList to keep order of elements.
  • HashMap 绝对不保证迭代顺序。当添加新元素时,它甚至可以(并且将会)完全改变。
  • LinkedHashMap 将按照条目放入映射的顺序进行迭代
  • 由于这种排序功能,LinkedHashMap 还需要比 HashMap 更多的内存。正如我之前所说的 LinkedHashMap 使用双重 LinkedList 来保持元素的顺序。

回答by Thomas Stets

In most cases when using a Map you don't care whether the order of insertion is maintained. Use a HashMap if you don't care, and a LinkedHashMap is you care.

在大多数情况下,当使用 Map 时,您并不关心插入的顺序是否保持不变。如果您不在乎,请使用 HashMap,而您在乎的是 LinkedHashMap。

However, if you look when and where maps are used, in many cases it contains only a few entries, not enough for the performance difference of the different implementations to make a difference.

然而,如果你看一下何时何地使用了映射,在很多情况下它只包含几个条目,不足以让不同实现的性能差异产生影响。