HashMap是先扩容还是优先树化

533 阅读1分钟

不同版本JDK的区别

  • jdk1.7中hashmap先扩容再插入
  • jdk1.8中hashmap为什么先插入再扩容

jdk7中hashmap为什么先扩容再插入

JDK1.7采用头插法,扩容后,计算hash,只需要插入链表头部就行

jdk8中hashmap为什么先插入再扩容

JDK1.8 Hashmap采用的是数组+链表+红黑树的数据结构

基本参数介绍

/**
 * The default initial capacity - MUST be a power of two.  
 *  * 桶的容量,默认16
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

/**
 * The maximum capacity, used if a higher value is implicitly specified
 * by either of the constructors with arguments.
 * MUST be a power of two <= 1<<30.    
 * * 桶的最大容量    
 * */  
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
 * The load factor used when none specified in constructor. 
 * * 负载因子
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
 * 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.  
 *  * 最小树化容量阀值即容量必要大于64才开始树化 
 *    * 避免树化和扩容冲突
 */
static final int MIN_TREEIFY_CAPACITY = 64;

JDK1.8采用尾插法,如果先扩容,扩容后需要遍历一遍,再找到尾部进行插入