HashMap数据结构
在jdk1.7中,HashMap采用数组+链表(拉链法)。因为数组是一组连续的内存空间,易查询,不易增删,而链表是不连续的内存空间,通过节点相互连接,易删除,不易查询。HashMap结合这两者的优秀之处来提高效率。
而在jdk1.8时,为了解决当hash碰撞过于频繁,而链表的查询效率(时间复杂度为O(n))过低时,当链表的长度达到一定值(默认是8)时,将链表转换成红黑树(时间复杂度为O(logn)),极大的提高了查询效率。
本文使用JDK8的HashMap源码进行解析
源码解读
DEFAULT_INITIAL_CAPACITY:HashMap的默认大小是16
MAXIMUM_CAPACITY:最大容量是2^30,如果指定的容量大于2^30,则使用2^30为最大容量
DEFAULT_LOAD_FACTOR:默认的负载因子为0.75
/**
* The default initial capacity - MUST be a power of two.
*/
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;
链表中的Node节点
Node节点是以内部类的方式实现的,将hash、key、value、next属性都封装在Node节点上
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
static class Node<K,V> implements Map.Entry<K,V> {
//key的Hash值
final int hash;
//key值
final K key;
//key对应的value值
V value;
//下一个Node的内存地址