1. 导读
经过上期的分享, 相信大家对HashMap已经有了个初步的印象, 今天将围绕下面几个问题展开:
.1 HashMap的数据结构在java中是如何设计的;
.2 HashMap序列化的问题;
2. hash槽长度的确定
我们将围绕下面HashMap的数据结构和关键代码来看HashMap的设计:
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final int MAXIMUM_CAPACITY = 1 << 30;
DEFAULT_INITIAL_CAPACITY定义了上图中hash槽的默认大小; 而MAXIMUM_CAPACITY则定义了hash槽的最大值;那么hash槽的长度是[2^4, 2^30], 设计者是采用了何种机制来实现这个的呢?
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |&#