如何获取 Java Hashmap 上冲突数量的指标?
我正在实现一个自定义哈希函数,如果我在 HashMap 存储桶中发生多次冲突,我如何知道存储桶中存储了多少元素?
I'm implementing a custom hash function, If I get a number of collisions into a HashMap bucket, how can I know how many elements are stored in the bucket?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
API 中没有对此直接支持。用于存储存储桶的成员变量
table
甚至不是公共的,因此扩展该类不会让您走得太远。假设您正在评估哈希函数而不是在生产代码中执行此操作,则可以使用反射来传递这些约束。
我设法打印了桶中的内容。从这一点来看,分析分布指标应该不难。代码如下:
测试驱动程序:
SubHashMap:
输出:
There is no direct support for this in the API. The member variable
table
, used for storing the buckets, is not even public, so extending the class won't get you far.Assuming you're evaluating hash functions and not doing this in production code, you can get passed these constraints using reflection.
I managed to print the content of the buckets. To analyze the distribution metrics shouldn't be hard from this point. Here's the code:
Test driver:
SubHashMap:
Output:
没有内置方法可以确定是否发生碰撞。您将必须研究集合(HashMap)如何将 hashCode 值分配到存储桶并自己镜像该过程,监视您的插入以跟踪冲突。
There's no builtin way to determine if a collision occurred. You will have to investigate how the collection (HashMap) distributes hashCode values to buckets and mirror the process yourself, monitoring your inserts to keep track of collisions.
您可以编写一些反射代码来访问 HashMap 的内部存储桶并自行检查它们。
you could write some reflective code to gain access to the internal buckets of the HashMap and inspect them yourself.