按照已设置的顺序对HashMap进行迭代 [英] Iterating HashMap on order it has been set

查看:104
本文介绍了按照已设置的顺序对HashMap进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



请考虑下面的代码:

  HashMap< String,String> map = new HashMap< String,String>(); 
map.put(ID,1);
map.put(Name,name);
map.put(Sort,sort);
map.put(Type,type);



(String key:map.keySet()){
System.out.println(key +:+ map.get (键));
}

和结果:

 名称:名称
排序:排序
类型:类型
ID:1

我需要迭代它才能放入条目。
任何帮助将不胜感激。

解决方案

顺序取决于 hashCode的结果()函数在你插入的键中,除非你做了一些奇怪的事情,它将会是随机的(但是一致的)。你正在寻找的是一个有排序的地图,例如 LinkedHashMap



查看一下哈希表在这里工作,如果你有兴趣的细节。


I've set a HashMap on certain order but it is iterated on a strange order!

Please consider code below:

HashMap<String, String> map = new HashMap<String, String>();
map.put("ID", "1");
map.put("Name", "the name");
map.put("Sort", "the sort");
map.put("Type", "the type");

...

for (String key : map.keySet()) {
    System.out.println(key + ": " + map.get(key));
}

and the result:

Name: the name
Sort: the sort
Type: the type
ID: 1

I need to iterate it in order i've put the entries. Any help will be appreciated.

解决方案

The order depends on the result of the hashCode() function in the keys you are inserting which, unless you did something strange, is going to be mostly random (but consistent). What you are looking for is a sorted map such as a LinkedHashMap

Check out a little bit about how hashtables work here if you are interested in the details.

这篇关于按照已设置的顺序对HashMap进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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