英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论