Hashtable与HashMap的区别(源码级)

首先他们的相同点都实现了Map接口,不同点有很多:
1. Hashtable 继续了抽象类Dictionary,所有Hashtable是线程安全的,而HashMap不是
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable {

2. Hashtable不能存放key为null的对象,它会抛出异常,而HashMap是可以的。
 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;
}
}

3. 初始化数组大小不一样,HashMap是16,而Hashtable是11
public Hashtable() {
this(11, 0.75f);
}

4. 扩容机制也不同,HashMap是旧的大小×2,而Hashtable是旧的大小×2+1
 protected void rehash() {
int oldCapacity = table.length;
Entry[] oldMap = table;

int newCapacity = oldCapacity * 2 + 1;
Entry[] newMap = new Entry[newCapacity];

modCount++;
threshold = (int)(newCapacity * loadFactor);
table = newMap;

for (int i = oldCapacity ; i-- > 0 ;) {
for (Entry<K,V> old = oldMap[i] ; old != null ; ) {
Entry<K,V> e = old;
old = old.next;

int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = newMap[index];
newMap[index] = e;
}
}
}

5. 计算数组下标index的方法不同:
Hashtable的如下
 int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;


HashMap的如下
/**
* 计算hashCode的方法
*/
static int hash(int h) {

h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}

/**
* 根据hashcode和数组的大小来计算数组下标的方法
*/
static int indexFor(int h, int length) {
return h & (length-1);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值