最近,在一次采访中我被问到,hashmap中的一个桶究竟是什么?无论是数组还是arraylist还是什么?
我很困惑。我知道哈希映射是由数组支持的。那么我可以说bucket在开始存储哈希码时是一个容量为16的数组,链接列表的起始指针是什么?我知道hashmap内部是如何工作的,只是想知道数据结构的确切含义。
答案 0 :(得分:23)
不,存储桶是您所指的数组中的每个元素。在早期的Java版本中,每个存储桶都包含一个Map条目的链接列表。在新的Java版本中,每个存储桶包含条目的树结构或条目的链接列表。
从Java 8中的实现说明:
/*
* Implementation notes.
*
* This map usually acts as a binned (bucketed) hash table, but
* when bins get too large, they are transformed into bins of
* TreeNodes, each structured similarly to those in
* java.util.TreeMap. Most methods try to use normal bins, but
* relay to TreeNode methods when applicable (simply by checking
* instanceof a node). Bins of TreeNodes may be traversed and
* used like any others, but additionally support faster lookup
* when overpopulated. However, since the vast majority of bins in
* normal use are not overpopulated, checking for existence of
* tree bins may be delayed in the course of table methods.
...
答案 1 :(得分:19)
答案 2 :(得分:4)
Buckets 正好是一个节点数组。因此,单个存储桶是类java.util.HashMap.Node的一个实例。每个Node都是一个类似于LinkedList的数据结构,或者可能像TreeMap(从Java 8开始),HashMap决定自己什么对性能更好 - 将桶保留为LinkedList或TreeMap。只有在设计不良的hashCode()函数的情况下才会选择TreeMap,当大量条目放在单个存储桶中时。 查看HashMap中的桶状态:
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;
答案 3 :(得分:0)
Buckets基本上是一种在操作系统的Paging算法中使用的数据结构。要使用非常Laymans语言。
表示特定哈希码的对象存储在该桶中。(基本上,您可以将链表数据结构的头部视为以桶为单位表示的哈希码值)
对象的引用存储在链接列表中,其标题表示Hashcode的值。
JVM创建它们的大小取决于JVM分配的内存。