I found following code in Java HashMap source code:
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
*/
static final int MIN_TREEIFY_CAPACITY = 64;
My doubt is this:
Q0. How these three variables together determine treeifying and untreeifying?
However the question above could be abstract as there might involve a lot of subtle facts that needs to be addressed in the answer to make it complete overall. As these are subtle facts and could possibly be overlooked in the answer, I tried to list them down in three separate questions below. You may answer Q0 or preferably Q1, Q2 and Q3.
I understood as follows:
We start with linked list for collision resolution. Once we insert a key which is to be hashed to the bucket already containing 8 (
TREEIFY_THRESHOLD
) keys and if there are already 64 (MIN_TREEIFY_CAPACITY
) keys in HashMap, linked list of that bucket is converted to balanced tree. If we delete a key from the bucket containing 6 keys in a balanced tree, then it is converted back to the linked list.
Q1. Is above understanding correct?
Q2. I didnt get why
UNTREEIFY_THRESHOLD
should be at most 6 to mesh with shrinkage detection under removal.
Q3. I didnt get why
MIN_TREEIFY_CAPACITY
should be at least4 * TREEIFY_THRESHOLD
to avoid conflicts between resizing and treeification thresholds.