gpt4 book ai didi

java - 如何从 iterator() 中以正确的顺序获取元素

转载 作者:搜寻专家 更新时间:2023-10-31 08:05:32 24 4
gpt4 key购买 nike

这是我将数据存储到 HashMap 并使用迭代器显示数据的代码

public static void main(String args[]) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("aaa", "111");
hm.put("bbb", "222");
hm.put("ccc", "333");
hm.put("ddd", "444");
hm.put("eee", "555");
hm.put("fff", "666");

Iterator iterator = hm.keySet().iterator();

while (iterator.hasNext()) {
String key = (String) iterator.next();
String val = hm.get(key);

System.out.println(key + " " + val);
}
}

但它不是按照我存储的顺序显示的。有人可以告诉我我哪里出错了吗?如何获取订单中的元素?

最佳答案

A HashMap没有保证顺序:

This class makes no guarantees as to the order of the map;

使用 LinkedHashMap .

Hash table and linked list implementation of the Map interface, with predictable iteration order.

关于java - 如何从 iterator() 中以正确的顺序获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6996191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com