简体   繁体   English

Map.entrySet()如何遍历hashMap

[英]How does Map.entrySet() traverse a hashMap

Suppose that I have a HashMap() defined and allocated like this: 假设我有如下定义和分配的HashMap()

private HashMap<Integer, Integer> rankCombinator=new HashMap<>();

I am always "building" the HashMap with keys and values before accessing it, for example I am storing 15 Integers on it as keys with their corresponding values I want. 在访问它之前,我总是用键和值“构建” HashMap,例如,我将15个整数作为键存储在键上,并带有所需的相应值。 I am trying to traverse this map using a for-each loop: 我试图使用for-each循环遍历此地图:

for(Map.Entry<Integer, Integer> entry : rankCombinator.entrySet())
{
   // More code here.
}

I suppose this loop won't return the values sorted in the way they were inputted in the the first place. 我想这个循环不会返回以它们最初输入方式排序的值。 Am I right? 我对吗? If yes, is there any pattern in the values returned? 如果是,返回的值中是否有任何模式? I have tried looking over the documentation but it doesn't seem like it includes a pattern for this. 我尝试查看文档,但似乎没有为此提供模式。

The HashMap implementation makes no guarantees about the order the items are returned, I would suggest using a LinkedHashMap which retains order. HashMap实现不能保证商品的返回顺序,我建议使用保留顺序的LinkedHashMap

private Map<Integer, Integer> rankCombinator=new LinkedHashMap<Integer, Integer>();

Api Documentation Api文档

Short answer, no. 简短的回答,不。 From the javadoc : "This class makes no guarantees as to the order of the map" 来自javadoc :“此类不保证地图的顺序”

It's arbitrary depending on the number of buckets in the hash table, and the order of elements in the buckets. 它是任意的,具体取决于哈希表中存储区的数量以及存储区中元素的顺序。 As such it varies when a rehash happens. 因此,当重新哈希发生时,它会有所不同。

Use a LinkedHashMap if you need predictable order based on insertion order. 如果您需要基于插入顺序的可预测顺序,请使用LinkedHashMap

Hash maps store items in "buckets" based on the hash code of the key. 哈希映射根据密钥的哈希码将项目存储在“存储桶”中。 The "plain" HashMap returns entries as it finds them in its "hash buckets". 当“普通” HashMap在其“哈希存储桶”中找到条目时,它们将返回条目。 There is no discernable pattern to it, and even if you find it, it would be heavily dependent on implementation and unreliable. 它没有可辨别的模式,即使找到它,它也将严重依赖于实现且不可靠。

If you need a reliable order of iteration, use either a TreeMap (you'll get entries sorted by key) or LinkedHashMap (you'll get insertion order). 如果需要可靠的迭代顺序,请使用TreeMap (您将获得按键排序的条目)或LinkedHashMap (您将获得插入顺序)。 Note that the TreeMap has a different mechanism of deciding the equality of its keys, so you would either make the keys comparable, or provide a comparator on the side to deal with the key ordering. 请注意, TreeMap具有决定其键是否相等的不同机制,因此您可以使键具有可比性,或者在侧面提供一个比较器来处理键排序。

The order is random, but is determined by the hash function which allocates objects to slots in the hashmap array store. 顺序是随机的,但是由哈希函数确定,该哈希函数将对象分配给哈希映射数组存储中的插槽。

More on that here: How does a hash table work? 此处的更多信息: 哈希表如何工作?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM