如何在哈希表中保留固定的键序列?
How to preserve the fixed sequence of keys in Hashtable?
此代码创建一个哈希表如下:
"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]);
}
但是,distr
中的键序列是随机的,例如
"10:00-11:00" - 0, "23:00-00:00" - 0, "00:00-01:00" - 0, ...
在 distr
中保存密钥时如何保留 intervals
中给出的序列?
改用 LinkedHashMap
,您将能够按插入顺序对其进行迭代。也可以在上次使用的配置中使用 LinkedHashMap
。
此代码创建一个哈希表如下:
"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]);
}
但是,distr
中的键序列是随机的,例如
"10:00-11:00" - 0, "23:00-00:00" - 0, "00:00-01:00" - 0, ...
在 distr
中保存密钥时如何保留 intervals
中给出的序列?
改用 LinkedHashMap
,您将能够按插入顺序对其进行迭代。也可以在上次使用的配置中使用 LinkedHashMap
。