HashMap的元素顺序错误 [英] elements of HashMap are in the wrong order

查看:92
本文介绍了HashMap的元素顺序错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从文件中读取两列(均为String),并将第一列的值保留在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是无序的.
枚举顺序由键的hascodes确定.

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的元素顺序错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆