Iterating HashMap on order it has been set(按已设置的顺序迭代 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按已设置的顺序迭代 HashMap


基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01