# HashMap，难的不在Map，而在Hash

### 01、Hash

Hash，一般译作“散列”，也有直接音译为“哈希”的，这玩意什么意思呢？就是把任意长度的数据通过一种算法映射到固定长度的域上（散列值）。

``````public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;

for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}``````

``````String[] cmower = { "沉", "默", "王", "二" };
for (String s : cmower) {
System.out.println(s.hashCode());
}``````

``````Map map = new HashMap<>();
String[] cmower = { "沉", "默", "王", "二" };
for (String s : cmower) {
map.put(s, s + "月入25万");
}``````

``````public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}``````

``````static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}``````

``````public V get(Object key) {
Node e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}``````

### 03、初始容量和负载因子

HashMap的构造方法主要有三种：

``````public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
this.threshold = tableSizeFor(initialCapacity);
}

public HashMap(int initialCapacity) {
}

public HashMap() {
}``````