elements of HashMap are in the wrong order(HashMap 的元素顺序错误)
问题描述
我需要从文件中读取两列(均为字符串),并将第一列的值保存在 HashMap 中,其中 Integer 是计数器.
I need to read two columns (both String) from a file and keep the values of the first column in a HashMap where the Integer is the counter.
例如,如果我正在阅读的文件是
For example if the file I am reading is
Apple Fruit
PC Device
Pen Tool
...
代码是
String line="";
int counter=1;
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt"),"Unicode"));
while ((line = reader.readLine()) != null)
{
String[] words;
words= st.split(" ");
tokens.put(counter, words[0]);
counter+=1;
}
问题是当我打印 HashMap 值时,我发现这些值的顺序与原始文件中的顺序不同
The problem is when I print The HashMap values, I found the values are in different order of that in the origianl file
for (Map.Entry<Integer, String> token:tokens.entrySet())
{
System.out.println(token.getKey() + token.getValue());
}
我得到了以下
1 Apple
3 Pen
4 whatever
2 ..etc
不知道是什么问题?!你能帮帮我吗
I do not know what is the problem?! can you please help me with that
推荐答案
正如文档明确指出的那样,HashMap 是无序的.
枚举顺序由键的hascode决定.
As the documentation clearly states, HashMaps are unordered.
The enumeration order is determined by the hascodes of the keys.
如果您想在枚举地图时保留插入顺序,请使用 LinkedHashMap
.
如果您希望枚举顺序遵循键的自然顺序,请使用 TreeMap
.
If you want to preserve insertion order when enumerating the map, use LinkedHashMap
.
If you want enumeration order to follow the natural ordering of the keys, use TreeMap
.
这篇关于HashMap 的元素顺序错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:HashMap 的元素顺序错误


基础教程推荐
- Java Swing计时器未清除 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01