---
title: "JDK源码学习-HashMap\\Hashtable"
author: "kayban"
date: "2011-10-08T09:23:19Z"
tags: []
categories: ["编程语言"]
slug: "jdk-hashmap-hashtable"
draft: false
lastmod: "2011-10-08T09:23:19Z"
id: 1186555
url: "https://ban.iteye.com/blog/1186555"
---

1、HashMap初始化容量

```java

   // Find a power of 2 >= initialCapacity
   int capacity = 1;
   while (capacity < initialCapacity)
            capacity <<= 1;

   this.loadFactor = loadFactor;
   threshold = (int)(capacity * loadFactor);
   table = new Entry[capacity];

```

注：初始容量是一个不小于initialCapacity且为2的倍数的数值，默认为16。
2、HashMap扩容resize()

```java

 if (size++ >= threshold)
            resize(2 * table.length);

```

注：以2倍形式扩容
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3、Hashtable初始化

```java

public Hashtable() {
	this(11, 0.75f);
    }

```

默认初始容量为11，加载因子为0.75
提供带参数的构造函数，初始容量区别于HashMap，没有2倍的限制。
4、Hashtable是同步的。
5、Hashtable不能存储null对象

```java

// Make sure the value is not null
	if (value == null) {
	    throw new NullPointerException();
	}

```

6、Hashtable扩容

```java

int newCapacity = oldCapacity * 2 + 1;

```

7、计算数组index的方法

```java

 index = (hash & 0x7FFFFFFF) % tab.length;

```