如何在哈希表中保持元素的顺序 [英] How to keep the order of elements in hashtable

查看:164
本文介绍了如何在哈希表中保持元素的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个哈希表。 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 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). 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 if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

Collections.synchronizedMap()

所以,例如:

Map<String, String> map = Collections.synchronizedMap(
  new LinkedHashMap<String, String>());

这篇关于如何在哈希表中保持元素的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆