HashMap元素的顺序是否可重现? [英] Is the order of HashMap elements reproducible?

查看:174
本文介绍了HashMap元素的顺序是否可重现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我想明确地说,我永远不会使用HashMap来做数据结构中需要某种顺序的事情,而且这个问题是由我对Java HashMap实现的内部细节的好奇心所激发的。



您可以阅读 Object c $ c> >方法 hashCode



我从那里了解到 hashCode 实现类,如 String 和基本类型包装器(整数 Long ,...)是可预测的。一个例子是调用 hashCode ,对于包含值 hello的任何 String 对象应该永远返回: 99162322



拥有一个总是插入空Java的算法HashMap其中 String s以同样的顺序用作相同值的键。那么最后它的元素的顺序应该是一样的,我错了吗?



由于具体值的哈希码总是一样的,如果没有碰撞,订单应该是一样的。
另一方面,如果有冲突,我认为(我不知道事实)冲突决议应该导致完全相同的输入元素相同的顺序。



所以,两个具有相同元素的HashMap对象是否以相同的顺序插入(由迭代器)遍历,给出相同的元素序列是不对的?

解决方案

据我所知,命令(假设我们称之为order)由 values() HashMap 中的元素的c $ c> iterator)保留,直到映射rehash被执行。我们可以通过向构造函数提供容量和/或 loadFactor 来影响该事件的可能性。



然而,我们不应该依赖此声明,因为 HashMap 的内部实现不是其公共合同的一部分,而是一个主题将来要改变。


First of all, I want to make it clear that I would never use a HashMap to do things that require some kind of order in the data structure and that this question is motivated by my curiosity about the inner details of Java HashMap implementation.

You can read in the java documentation on Object about the Object method hashCode.

I understand from there that hashCode implementation for classes such as String and basic types wrappers (Integer, Long,...) is predictable once the value contained by the object is given. An example of that would be that calls to hashCode for any String object containing the value hello should return always: 99162322

Having an algorithm that always insert into an empty Java HashMap where Strings are used as keys the same values in the same order. Then, the order of its elements at the end should be always the same, am I wrong?

Since the hash code for a concrete value is always the same, if there are not collisions the order should be the same. On the other hand, if there are collisions, I think (I don't know the facts) that the collisions resolutions should result in the same order for exactly the same input elements.

So, isn't it right that two HashMap objects with the same elements, inserted in the same order should be traversed (by an iterator) giving the same elements sequence?

解决方案

As far as I know the order (assuming we call "order" the order of elements as returned by values() iterator) of the elements in HashMap are kept until map rehash is performed. We can influence on probability of that event by providing capacity and/or loadFactor to the constructor.

Nevertheless, we should never rely on this statement because the internal implementation of HashMap is not a part of its public contract and is a subject to change in future.

这篇关于HashMap元素的顺序是否可重现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆