What is a bucket in hashmap?

Recently in an interview I was asked what a hashmap bucket is? Is it an array or an arraist or what?

I'm confused. I know that hashmaps are supported by arrays. So, can I say that the bucket is an array with a capacity of 16 at the beginning of the storage of hash codes and to which the linked lists have their own pointer to the beginning?

I know how the hashmap internally works, I just wanted to find out what exactly the bucket is in terms of data structure.

+8
source share
4 answers

No, a bucket is every element of the array that you are accessing. In earlier versions of Java, each bucket contained a linked list of Maps entries. In newer versions of Java, each bucket contains either a tree-like structure of entries or a linked list of entries.

From the implementation notes in 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. ... 
+16
source

bucket

Hope this helps you understand the hash map implementation well.

+13
source

Buckets are basically a data structure that is used in the Paging algorithm of the operating system. Be in the language of Laymans.

Objects representing a specific hash code are stored in this bucket. (basically you can consider the header of the data structure of the linked list as a hash code value, which is presented in terms of a bucket)

Links to the object are stored in the list of links whose title represents the Hashcode value.

The JVM creates them, and the size depends on how much memory the JVM allocates.

0
source

Buckets accurately represent an array of nodes. Thus, one bucket is an instance of the java.util.HashMap.Node class. Each Node is a LinkedList-like data structure, or can be like a TreeMap (starting with Java 8), HashMap decides what is best for performance - save the buckets as LinkedList or TreeMap. TreeMap will be selected only in case of a poorly designed hashCode () function, when many records will be placed in one bucket. See what buckets look like in a 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; 
0
source

Source: https://habr.com/ru/post/1274392/


All Articles