哈希表是按字母顺序排列的? [英] Hashmap is put into alphabetical order?

查看:122
本文介绍了哈希表是按字母顺序排列的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HashMap定义如下:

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

当我将新条目放到这个HashMap中时,它们最终以字母顺序为基础。它为什么这样做?如何将它们添加到HashMap中?

解决方案 HashMap 没有明确定义你添加的元素的顺序。就像在 HashSet 中,元素是通过它们的哈希码进行订购的,这或多或少是随机的。 如果你想要按照插入顺序保存地图中的顺序,您可以使用 LinkedHashMap 。或者如果元素应该使用 TreeMap 在插入后排序。

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?

解决方案

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.

这篇关于哈希表是按字母顺序排列的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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