java -- HashMap详解

什么是hash

比较官方的解释是将任意长度数据映射到到固定长度的域中。

例如我们要将1~100编号的苹果放在10个篮子中,怎么做才能尽可能均匀地分散这100个苹果,使得每个篮子苹果个数大致相当。最简单的办法就是通过模运算来解决,把每一个苹果的编号num对篮子数n进行取模得到该苹果要放入篮子的编号index,即index=num%n。这样,可以保证每个篮子都将放入10个苹果。

hash在Map中的应用

HashMap的底层是HashTable,通过Node[]进行数据存储;每一个Node是一个key-value键值对,在进行Node存放,即确定节点在Node[]中的存储index时,采用了Hash散列的思想。由于Hash散列的随机性,有时候会出现不同Node同一index的情况,这时候HashMap采用了同一index处采用链表的形式来存储相同index的不同Node

HashMap所在包

HashMap位于java.util包下,使用它必须导包。

HashMap构造函数

HashMap有4个构造函数,源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
 /**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
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);
}

/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
* Constructs a new <tt>HashMap</tt> with the same mappings as the
* specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
* default load factor (0.75) and an initial capacity sufficient to
* hold the mappings in the specified <tt>Map</tt>.
*
* @param m the map whose mappings are to be placed in this map
* @throws NullPointerException if the specified map is null
*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}

一般情况下,我们默认使用空参构造函数,只有在特殊情况需要调节HashMap性能时会使用包含initialCapacityloadFactor含参构造函数。

HashMap的底层实现