hashmap and hashtable 区别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//HashMap的源码
public class HashMap<K,V>
     extends AbstractMap<K,V>
     implements Map<K,V>, Cloneable, Serializable{
  //HashMap的put方法,没有同步
  public V put(K key, V value){
   ...
   if (key ==  null )
    return putForNullKey(value);
   ...
  }
  
  //以下是HashMap中的方法,注意,没有contains方法
  public boolean containsKey(Object key) {...}
  public boolean containsValue(Object value){...}
  
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//Hashtable的源码
public class Hashtable<K,V>
     extends Dictionary<K,V>
     implements Map<K,V>, Cloneable, java.io.Serializable{
  //Hashtable的put方法
  //当然,Hashtable的其他方法,如get,size,remove等方法,
  //都加了synchronized关键词同步操作
  public synchronized V put(K key, V value){
   ...
   if (value ==  null ) {
       throw new NullPointerException();
   }
   ...
  }
  //以下是Hashtable的方法
  public synchronized boolean contains(Object value);
  public synchronized boolean containsKey(Object key);
  public boolean containsValue(Object value);
}

1、继承不同。public class Hashtable extends Dictionary implements Map

 public class HashMap extends AbstractMap implements Map

2、Hashtable 中的方法是同步的,而HashMap中的方法在缺省情况下是非同步的。在多线程并发的环境下,可以直接使用Hashtable,但是要使用HashMap的话就要自己增加同步处理了。

3、Hashtable中,key和value都不允许出现null值。

在HashMap中,null可以作为键,这样的键只有一个;可以有一个或多个键所对应的值为null。当get()方法返回null值时,即可以表示 HashMap中没有该键,也可以表示该键所对应的值为null。因此,在HashMap中不能由get()方法来判断HashMap中是否存在某个键, 而应该用containsKey()方法来判断。

4、两个遍历方式的内部实现上不同。

Hashtable、HashMap都使用了 Iterator。而由于历史原因,Hashtable还使用了Enumeration的方式 。

5、哈希值的使用不同,HashTable直接使用对象的hashCode。而HashMap重新计算hash值。

6Hashtable和HashMap它们两个内部实现方式的数组的初始大小和扩容的方式。HashTable中hash数组默认大小是11,增加的方式是 old*2+1。HashMap中hash数组的默认大小是16,而且一定是2的指数 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值