本文介绍了如何对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()
    );
}

推荐答案

如果您想要保留订单的地图,则应使用 LinkedHashMap :

If you want an order-preserving map, you should use LinkedHashMap:

此实现使客户免于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进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:10
查看更多