Hashmap is put into alphabetical order?

拈花ヽ惹草 提交于 2019-12-24 04:32:34

问题


I have a HashMap defined as follow:

private final Map<String, DataTable> reports = new HashMap();

When I put new entries into this HashMap they end up in Alphabetical order based on the key. Why is it doing this? How do I put them in the order I added them to the HashMap?


回答1:


A HashMap does explicitly define NO order of the elements you add. Like in a HashSet the elements are ordery by their hashcode and this is more or less random.

If you want to preserve the order in the Map in the order of insertion you can use a LinkedHashMap instead. Or use a TreeMap if the elements should be sorted after the insertion.




回答2:


The whole point of a HashMap is that you surrender control of the ordering, so that you can get performance gains on inserting and searching, and other benefits. To take back control of the ordering, look into using a SortedMap.




回答3:


LinkedHashMap- preserve the insertion order.
TreeMap - Elements sorted after insertion.

HashMap doesn't maintain any order of inserted elements.




回答4:


HashMap doesn't add the values in the way you are adding it just adds the value randomly based on keys. For adding the values in the order you are adding use LinkedHashMap or if you want the Map in Alphabetically sorted order then use TreeMap. I hope this clears your doubt.



来源:https://stackoverflow.com/questions/45574080/hashmap-is-put-into-alphabetical-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!