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

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

问题描述

我已经按特定顺序设置了 HashMap,但它以奇怪的顺序迭代!

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

请考虑以下代码:

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));
}

结果:

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.

推荐答案

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

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天全站免登陆