【发布时间】:2013-05-27 15:04:09
【问题描述】:
我需要从文件中读取两列(均为字符串),并将第一列的值保存在 HashMap 中,其中 Integer 是计数器。
例如,如果我正在阅读的文件是
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 值时,我发现这些值的顺序与原始文件中的顺序不同
for (Map.Entry<Integer, String> token:tokens.entrySet())
{
System.out.println(token.getKey() + token.getValue());
}
我得到了以下
1 Apple
3 Pen
4 whatever
2 ..etc
不知道是什么问题?!你能帮帮我吗
【问题讨论】:
-
您将需要使用不同的容器。 hashmap 实现的本质几乎保证了原始顺序不会被保留。
-
你认为这里的正确顺序是什么?
-
取决于密钥!