---
title: "关于Hashtable和HashMap， Vector和ArrayList"
author: "JackyCheng2007"
date: "2012-05-01T09:41:01Z"
tags: []
categories: ["编程语言"]
slug: "hashtable-hashmap-vector-arraylist"
draft: false
lastmod: "2012-05-01T17:31:20Z"
id: 1506303
url: "https://jackycheng2007.iteye.com/blog/1506303"
---

在功能上讲Hashtable和HashMap， Vector和ArrayList有着几乎相同的功能。他们的主要区别在于：
Hashtable和HashMap的区别，先看put方法的源代码
Hashtable

```java

public synchronized V put(K key, V value) {
	// Make sure the value is not null
	if (value == null) {
	    throw new NullPointerException();
	}

	// Makes sure the key is not already in the hashtable.
	Entry tab[] = table;
	int hash = key.hashCode();
	int index = (hash & 0x7FFFFFFF) % tab.length;
	for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
	    if ((e.hash == hash) && e.key.equals(key)) {
		V old = e.value;
		e.value = value;
		return old;
	    }
	}

	modCount++;
	if (count >= threshold) {
	    // Rehash the table if the threshold is exceeded
	    rehash();

            tab = table;
            index = (hash & 0x7FFFFFFF) % tab.length;
	}

	// Creates the new entry.
	Entry<K,V> e = tab[index];
	tab[index] = new Entry<K,V>(hash, key, value, e);
	count++;
	return null;
    }

```

HashMap

```java

public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

```

从源代码上看，区别就很明显了：
1. Hashtable里面的方法是同步的（synchronized），而HashMap不是。换句话说Hashtable是线程安全的，HashMap不是。在单线程条件下，HashMap比Hashtable快。
2. Hashtable不接受null值，HashMap接受。Hashtable也不接受null key，而HashMap接受。运行下面的代码，就知道Hashtable 的put会抛出NullPointerException。只是在源代码中对value的null做了check，并且显示的抛出异常，而对于key，这是在调用int hash = key.hashCode();的时候自动抛出的。

```java

HashMap hm = new HashMap();
		hm.put(null, null);
		Hashtable ht = new Hashtable();
		ht.put("OK", null);
		ht.put(null, "OK");

```


Vector和ArrayList也类似，他们唯一的区别就是Vector里面的方法是同步的（synchronized），而ArrayList不是。

JDK5 开始引入了concurrent包，里面包含ConcurrentHashMap，可以用在多线程环境下来代替Hashtable。
但是为什么没有一个类来代替Vector呢？