如何在哈希表中保持元素的顺序 [英] How to keep the order of elements in hashtable
问题描述
我有一个哈希表。 values()方法以不同于我插入顺序的顺序返回值。如何以与插入时相同的顺序获取值?使用LinkedHashmap是另一种选择,但它不同步。
I have a hashtable . values() method returns values in some order different from the order in which i am inserted.How can i get the values in the same order as i inserted?Using LinkedHashmap is an alternative but it is not synchronized.
推荐答案
使用 LinkedHashMap
。
哈希表和链表
实现Map
接口,
具有可预测的迭代顺序。这个
实现与
中的HashMap
不同,它维护了一个双向链表
,贯穿其所有条目。
此链接列表定义迭代
排序,通常是订单
,其中键被插入
地图(插入订单)。请注意,如果
键重新插入到地图中,则
广告订单不会受到影响。 (如果在
<$ c时调用
m.put(k,v)
,则将
密钥k重新插入到地图m中$ c> m.containsKey(k)将在调用之前立即返回true
。)
Hash table and linked list implementation of the
Map
interface, with predictable iteration order. This implementation differs fromHashMap
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). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m ifm.put(k, v)
is invoked whenm.containsKey(k)
would returntrue
immediately prior to the invocation.)
与 Collections.synchronizedMap()
。
所以,例如:
Map<String, String> map = Collections.synchronizedMap(
new LinkedHashMap<String, String>());
这篇关于如何在哈希表中保持元素的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!