java HashMap.entrySet()方法是否按插入顺序遍历HashMap?

huangapple go评论70阅读模式
英文:

Does java HashMap.entrySet() iterate through the HashMap in order of insertion?

问题

在遍历整数到字符串的哈希映射时,假设我按以下顺序插入值

HashMap<Integer, String> hash_map = new HashMap<>();
hash_map.put(0, "check");
hash_map.put(1, "ok");
hash_map.put(2, "what");
hash_map.put(4, "why");

当我通过使用hash_map.entrySet()来遍历哈希映射时,我会按插入的顺序遍历吗?还是会以随机顺序遍历?

英文:

While iterating through the HashMap of Integer to String, suppose I insert values in the following order

HashMap<Integer, String> hash_map = new HashMap<>();
hash_map.put(0, "check");
hash_map.put(1, "ok");
hash_map.put(2, "what");
hash_map.put(4, "why");

When I iterate through the HashMap, using hash_map.entrySet(), will I iterate through it in order of insertion? Or will it be a random order?

答案1

得分: 2

当您需要一个地图,并且不关心顺序(在遍历时),那么HashMap是正确的选择。

如果您想保持插入的顺序,请尝试使用LinkedHashMap

尝试阅读这个链接:https://www.w3resource.com/java-tutorial/java-maps.php

英文:

When you need a Map and you don't care about the order (when you iterate through it), then HashMap is the right choice.

If you want the order of insertion try LinkedHashMap

try reading this : https://www.w3resource.com/java-tutorial/java-maps.php

huangapple
  • 本文由 发表于 2020年8月9日 03:59:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63319715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定