HashMap 的元素顺序错误

elements of HashMap are in the wrong order(HashMap 的元素顺序错误)

本文介绍了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 的元素顺序错误

基础教程推荐