问题描述
我正在尝试找出/可以检索 HashMap 中的值的顺序.这是相同的代码片段.
I am trying figure out the order in which the values in a HashMap are/can be retrieved. Heres the code snippet for the same.
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
hashmap.put(1, "apple" );
hashmap.put(2, "lemon" );
hashmap.put(3, "orange" );
hashmap.put(4, "banana" );
hashmap.put(5, "litchi" );
hashmap.put(6, "mango" );
hashmap.put(7, "papaya" );
System.out.println(hashmap.size());
for (String key : hashmap.values()) {
System.out.println(key);
}
}
}
输出:
7
apple
lemon
orange
banana
litchi
mango
papaya
这些值按照插入的顺序打印.这是真的吗?我期望这些值以任意顺序打印.这是使用 Java 6.
The values are printed in the order in which they have been inserted. Is this true in general? I was expecting the values to be printed in an arbitrary order. This is using Java 6.
推荐答案
这些值按照插入的顺序打印.这是真的吗?我期望这些值以随机顺序打印.
The values are printed in the order in which they have been inserted. Is this true in general? I was expecting the values to be printed in random order.
HashMap
API 没有定义迭代的顺序.
The HashMap
API does not define the order of iteration.
但是,如果您查看 HashMap 的实现,您可以推断出迭代顺序、键的哈希值、键的插入顺序和哈希表的大小之间存在复杂的瞬态关系.如果哈希表自行调整大小,这种关系就会被打乱.
However, if you look at the implementation of HashMap, you can deduce that there is a complex transient relationship between the iteration order, the keys' hash values, the order in which the keys were inserted and the size of the hashtable. This relationship gets scrambled if the hashtable resizes itself.
在您的情况下,您使用的是 Integer
键,这意味着键的哈希值就是键值本身.此外,您按密钥顺序插入了条目.这导致(幸运的是!)迭代顺序与插入顺序相匹配.但是如果你不断插入更多的键,你会发现迭代顺序环绕".然后随着表格经过一系列调整大小,顺序将逐渐变得越来越混乱.
In your case, you are using Integer
keys which means that the hash values of the keys are the key values themselves. Also, you inserted the entries in key order. This leads (fortuitously!) to the iteration order matching the insertion order. But if you kept inserting more keys, you would find that the iteration order "wraps around". Then as the table goes through a series of resizes, the order will get progressively more and more scrambled.
简而言之,您所看到的是哈希表实现的人工制品,而不是您可以(或应该)明智地使用的东西.尤其是因为它可能从一个 Java 版本更改为下一个.
In short, what you are seeing is an artefact of the hashtable implementation, and not something that you can (or should) sensibly make use of. Not least because it could change from one Java release to the next.
这篇关于从 HashMap 中检索的值的顺序是插入顺序吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!