简体   繁体   English

如何在哈希表中保留键的固定顺序?

[英]How to preserve the fixed sequence of keys in Hashtable?

This code create a Hashtable as follows: 此代码创建一个哈希表,如下所示:

"00:00-01:00" - 0, "01:00-02:00" - 0, ..., "23:00-00:00" - 0

Hashtable<String,Integer> distr = new Hashtable<String,Integer>();
numHoursPerDay = 24;
int interval;
int[] count = new int[numHoursPerDay];
String[] intervals = new String[numHoursPerDay];

for (int h = 0 ; h != 24 ; h++) {
    intervals[h] = String.format("%02d:00-%02d:00", h, ((h+1)%24));
    distr.put(intervals[h], count[h]);
}

However, the sequence of keys in distr is random, eg 但是, distr键的顺序是随机的,例如

"10:00-11:00" - 0, "23:00-00:00" - 0, "00:00-01:00" - 0, ...

How can I preserve the sequence given in intervals when saving keys in distr ? 将密钥保存在distr时,如何保留intervals给定的序列?

Use a LinkedHashMap instead, you will be able to iterate it in insertion order. 改用LinkedHashMap ,您将可以按插入顺序对其进行迭代。 It's also possible to use a LinkedHashMap in a last-used configuration. 也可以在最后使用的配置中使用LinkedHashMap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM