我需要将结果集转换为 map 中的 map 。 我不使用 map 列表的原因是因为我不想遍历整个列表来获取特定行。
我现在面临的问题是,如果索引大于 16,HashMap 的条目将不再排序。
现在我尝试了以下简单测试:
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<Integer, String>();
//creating 20 rows from 1 to 20
for (int i = 1; i <= 20; i++){
map.put(i, "ROW "+i);
}
//returning all the rows the map contains. Look at position 16.
for(int key : map.keySet()){
System.out.println(key);
}
}
输出如下(查看位置 16 到 20。它们完全无序):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 17 16 19 18 20
如果有人能解释为什么会这样,我将不胜感激。
顺便说一句:
我不能用这样的东西:
for (int i = 0; i < map.size; i++){
map.get(i) //...and so on
}
因为我不知道索引是否存在。可能是200到800的索引不存在。因此,最好只遍历 map 的现有条目。
最佳答案
HashMap
没有排序。如果您需要插入顺序 Map
,请使用 java.util.LinkedHashMap
。
如果您需要按键排序的 Map
,请使用 SortedMap
,例如 java.util.TreeMap
关于Java Map<Integer, HashMap<String, String>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10659134/