如何对Java Hashtable进行排序? [英] How to sort a Java Hashtable?
问题描述
我在Java Hashtable中插入了一些数据.如果我从哈希表读取数据,则返回的顺序与插入时的顺序不同.如何从哈希表中获取排序的数据?
I inserted some data into a Java Hashtable. If I read the data from the Hashtable it doesn't come back in the same order that I inserted it in. How do I get the ordered data from the Hashtable?
我使用以下代码从哈希表中获取值:
I use the following code to get the values from the hashtable:
// Get a set of the entries
Set set = hsUpdateValues.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.print(
"Key : " + me.getKey()
+ ", Value: " + me.getValue()
);
}
推荐答案
If you want an order-preserving map, you should use LinkedHashMap
:
Map接口的哈希表和链表实现,具有可预测的迭代顺序.此实现与HashMap的不同之处在于,它维护一个贯穿其所有条目的双向链接列表.此链表定义了迭代顺序,通常是将键插入映射的顺序(插入顺序).请注意,如果将密钥重新插入到映射中,则插入顺序不会受到影响. (如果在调用前
m.containsKey(k)
返回true时调用了m.put(k, v)
,则将键k
重新插入到映射m
中.)
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 mapm
ifm.put(k, v)
is invoked whenm.containsKey(k)
would return true immediately prior to the invocation.)
此实现使客户免于HashMap
(和Hashtable
)提供的未指定的,通常混乱的排序,而不会导致与TreeMap
相关的成本增加.
This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashMap
(and Hashtable
), without incurring the increased cost associated with TreeMap
.
请注意,通常将它与HashMap
而不是Hashtable
进行比较-我不知道与Hashtable
保持顺序的等价物;不管怎么说,后者现在通常都不会使用(就像ArrayList
通常优先于Vector
一样使用).
Note that this is usually compared with HashMap
rather than Hashtable
- I don't know of an order-preserving equivalent to Hashtable
; the latter isn't usually used these days anyway (just as ArrayList
is usually used in preference to Vector
).
我假设您想要的是插入顺序,而不是键排序顺序.如果需要后者,请使用 TreeMap
.
I've assumed you want insertion order rather than key-sorted order. If you want the latter, use TreeMap
.
这篇关于如何对Java Hashtable进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!