HashMap的参数总结

通过前面的解析,我们大致把HashMap的数据结构,put方法的存储过程,get及相关方法的查询过程和remove方法的移除过程解析了一遍,
接下来我们看一下面试中常会问到的参数,其实我们前面都接触到了,只是这里单独拿出来总结一下。

默认初始化容量

1
2
3
4
5
/**
* The default initial capacity - MUST be a power of two.
* 默认初始化容量,必须是2的次方
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

默认初始化容量。这个是在采用无参构造方法实例化HashMap的时候,默认使用16作为初始化容量。在第一次put的时候使用16来创建数组。

最大容量

1
2
3
4
5
6
7
8

/**
* 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.
* 最大容量。即HashMap的数组容量必须小于等于 1 << 30
*/
static final int MAXIMUM_CAPACITY = 1 << 30;

最大容量。但必须是2的次方数,我们来看下面这段代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
//如果初始化容量大于最大容量,则仅初始化为最大容量。
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}

可以看到,在指定容量的进行初始化时,会先判断这个初始化容量是否大于最大容量,超过则使用最大容量来进行初始化。

默认负载因子

1
2
3
4
5
/**
* The load factor used when none specified in constructor.
* 默认的负载因子
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;

默认负载因子;默认负载因子值为0.75,但是可以通过构造方法来指定。一般是不建议修改的。

树形化阈值

1
2
3
4
5
6
7
8
9
/**
* 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;

树形化阈值;即当链表的长度大于8的时候,会将链表转为红黑树,优化查询效率。链表查询的时间复杂度为o(n) , 红黑树查询的时间复杂度为 o(log n )

解树形化阈值

1
2
3
4
5
6
/**
* 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;

解树形化阈值;其实就是当红黑树的节点的个数小于等于6时,会将红黑树结构转为链表结构。

树形化的最小容量

1
2
3
4
5
6
7
/**
* 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;

树形化的最小容量;前面我们看到有一个树形化阈值,就是当链表的长度大于8的时候,会从链表转为红黑树。其实不一定是这样的。转为红黑树有两个条件:

  • ① 链表的长度大于8
  • ② HashMap数组的容量大于等于64

需要当上述两个条件都成立的情况下,链表结构才会转为红黑树。

#

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×