1、说说Hashtable和HashMap的区别

笔试面试题目搜集整理【每日增加】

1、说说Hashtable和HashMap的区别

 

【答案】

(1).HashMap 类没有分类或者排序。它允许一个 null 键和多个 null 值。
(2).Hashtable 类似于 HashMap,但是不允许 null 键和 null 值。它也比 HashMap 慢,因为它是同步的,线程安全的。
(3).Hashtable继承自Dictionary类,而HashMap是Java1.2引进的Map interface的一个实现。后者为Map的骨干, 其内部已经实现了Map所需要做的大部分工作, 它的子类只需要实现它的少量方法即可具有Map的多项特性。而前者内部都为抽象方法,需要它的实现类一一作自己的实现,且该类已过时。
(4).HashMap允许将null作为一个entry的key或者value,而Hashtable不允许,还有就是,HashMap把Hashtable的contains方法去掉了,改成containsvalue(Returns true if this map maps one or more keys to the specified value)和containsKey(Returns true if this map contains a mapping for the specified key)。因为contains(Tests if some key maps into the specified value in this hashtable)方法容易让人引起误解。
(5)两者检测是否含有key时,hash算法不一致,HashMap内部需要将key的hash码重新计算一边再检测,而 Hashtable则直接利用key本身的hash码来做验证.

 HashMap:

int hash = (key == null) ? 0 : hash(key.hashCode());
-----
static int hash(int h) {
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

 Hashtable:

int hash = key.hashCode(); 

(6).最大的不同是,Hashtable的方法是Synchronize的,而HashMap不是,在多个线程访问Hashtable时,不需要自己为它的方法实现同步,而HashMap 就必须为之提供外同步。
Hashtable和HashMap采用的hash/rehash算法都大概一样,所以性能不会有很大的差异。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值